es6.js 4.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346
  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. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. var finalVertexCode;
  143. this._loadVertexShaderAsync(vertexSource)
  144. .then(function (vertexCode) {
  145. return _this._processIncludesAsync(vertexCode);
  146. })
  147. .then(function (vertexCodeWithIncludes) {
  148. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  149. return _this._loadFragmentShaderAsync(fragmentSource);
  150. })
  151. .then(function (fragmentCode) {
  152. return _this._processIncludesAsync(fragmentCode);
  153. })
  154. .then(function (fragmentCodeWithIncludes) {
  155. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  156. if (baseName) {
  157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  159. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  160. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  161. }
  162. else {
  163. _this._vertexSourceCode = finalVertexCode;
  164. _this._fragmentSourceCode = migratedFragmentCode;
  165. }
  166. _this._prepareEffect();
  167. });
  168. }
  169. Object.defineProperty(Effect.prototype, "key", {
  170. get: function () {
  171. return this._key;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. // Properties
  177. Effect.prototype.isReady = function () {
  178. return this._isReady;
  179. };
  180. Effect.prototype.getEngine = function () {
  181. return this._engine;
  182. };
  183. Effect.prototype.getProgram = function () {
  184. return this._program;
  185. };
  186. Effect.prototype.getAttributesNames = function () {
  187. return this._attributesNames;
  188. };
  189. Effect.prototype.getAttributeLocation = function (index) {
  190. return this._attributes[index];
  191. };
  192. Effect.prototype.getAttributeLocationByName = function (name) {
  193. var index = this._attributesNames.indexOf(name);
  194. return this._attributes[index];
  195. };
  196. Effect.prototype.getAttributesCount = function () {
  197. return this._attributes.length;
  198. };
  199. Effect.prototype.getUniformIndex = function (uniformName) {
  200. return this._uniformsNames.indexOf(uniformName);
  201. };
  202. Effect.prototype.getUniform = function (uniformName) {
  203. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  204. };
  205. Effect.prototype.getSamplers = function () {
  206. return this._samplers;
  207. };
  208. Effect.prototype.getCompilationError = function () {
  209. return this._compilationError;
  210. };
  211. // Methods
  212. Effect.prototype.executeWhenCompiled = function (func) {
  213. if (this.isReady()) {
  214. func(this);
  215. return;
  216. }
  217. this.onCompileObservable.add(function (effect) {
  218. func(effect);
  219. });
  220. };
  221. /** @ignore */
  222. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  223. if (BABYLON.Tools.IsWindowObjectExist()) {
  224. // DOM element ?
  225. if (vertex instanceof HTMLElement) {
  226. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  227. return Promise.resolve(vertexCode);
  228. }
  229. }
  230. // Base64 encoded ?
  231. if (vertex.substr(0, 7) === "base64:") {
  232. var vertexBinary = window.atob(vertex.substr(7));
  233. return Promise.resolve(vertexBinary);
  234. }
  235. // Is in local store ?
  236. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  237. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  238. }
  239. var vertexShaderUrl;
  240. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  241. vertexShaderUrl = vertex;
  242. }
  243. else {
  244. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  245. }
  246. // Vertex shader
  247. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  248. };
  249. /** @ignore */
  250. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  251. if (BABYLON.Tools.IsWindowObjectExist()) {
  252. // DOM element ?
  253. if (fragment instanceof HTMLElement) {
  254. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  255. return Promise.resolve(fragmentCode);
  256. }
  257. }
  258. // Base64 encoded ?
  259. if (fragment.substr(0, 7) === "base64:") {
  260. var fragmentBinary = window.atob(fragment.substr(7));
  261. return Promise.resolve(fragmentBinary);
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  266. }
  267. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  268. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  269. }
  270. var fragmentShaderUrl;
  271. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  272. fragmentShaderUrl = fragment;
  273. }
  274. else {
  275. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  276. }
  277. // Fragment shader
  278. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  279. };
  280. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  281. // Rebuild shaders source code
  282. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  283. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  284. vertexCode = prefix + vertexCode;
  285. fragmentCode = prefix + fragmentCode;
  286. // Number lines of shaders source code
  287. var i = 2;
  288. var regex = /\n/gm;
  289. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  290. i = 2;
  291. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. // Dump shaders name and formatted source code
  293. if (this.name.vertexElement) {
  294. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  295. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  296. }
  297. else if (this.name.vertex) {
  298. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  299. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  300. }
  301. else {
  302. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  303. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  304. }
  305. };
  306. ;
  307. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  308. var preparedSourceCode = this._processPrecision(sourceCode);
  309. if (this._engine.webGLVersion == 1) {
  310. return preparedSourceCode;
  311. }
  312. // Already converted
  313. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  314. return preparedSourceCode.replace("#version 300 es", "");
  315. }
  316. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  317. // Remove extensions
  318. // #extension GL_OES_standard_derivatives : enable
  319. // #extension GL_EXT_shader_texture_lod : enable
  320. // #extension GL_EXT_frag_depth : enable
  321. // #extension GL_EXT_draw_buffers : require
  322. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  323. var result = preparedSourceCode.replace(regex, "");
  324. // Migrate to GLSL v300
  325. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  326. result = result.replace(/attribute[ \t]/g, "in ");
  327. result = result.replace(/[ \t]attribute/g, " in");
  328. if (isFragment) {
  329. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  330. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  331. result = result.replace(/texture2D\s*\(/g, "texture(");
  332. result = result.replace(/textureCube\s*\(/g, "texture(");
  333. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  334. result = result.replace(/gl_FragColor/g, "glFragColor");
  335. result = result.replace(/gl_FragData/g, "glFragData");
  336. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  337. }
  338. return result;
  339. };
  340. Effect.prototype._processIncludesAsync = function (sourceCode) {
  341. var _this = this;
  342. return new Promise(function (resolve, reject) {
  343. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  344. var match = regex.exec(sourceCode);
  345. var returnValue = sourceCode;
  346. while (match != null) {
  347. var includeFile = match[1];
  348. // Uniform declaration
  349. if (includeFile.indexOf("__decl__") !== -1) {
  350. includeFile = includeFile.replace(/__decl__/, "");
  351. if (_this._engine.supportsUniformBuffers) {
  352. includeFile = includeFile.replace(/Vertex/, "Ubo");
  353. includeFile = includeFile.replace(/Fragment/, "Ubo");
  354. }
  355. includeFile = includeFile + "Declaration";
  356. }
  357. if (Effect.IncludesShadersStore[includeFile]) {
  358. // Substitution
  359. var includeContent = Effect.IncludesShadersStore[includeFile];
  360. if (match[2]) {
  361. var splits = match[3].split(",");
  362. for (var index = 0; index < splits.length; index += 2) {
  363. var source = new RegExp(splits[index], "g");
  364. var dest = splits[index + 1];
  365. includeContent = includeContent.replace(source, dest);
  366. }
  367. }
  368. if (match[4]) {
  369. var indexString = match[5];
  370. if (indexString.indexOf("..") !== -1) {
  371. var indexSplits = indexString.split("..");
  372. var minIndex = parseInt(indexSplits[0]);
  373. var maxIndex = parseInt(indexSplits[1]);
  374. var sourceIncludeContent = includeContent.slice(0);
  375. includeContent = "";
  376. if (isNaN(maxIndex)) {
  377. maxIndex = _this._indexParameters[indexSplits[1]];
  378. }
  379. for (var i = minIndex; i < maxIndex; i++) {
  380. if (!_this._engine.supportsUniformBuffers) {
  381. // Ubo replacement
  382. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  383. return p1 + "{X}";
  384. });
  385. }
  386. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  387. }
  388. }
  389. else {
  390. if (!_this._engine.supportsUniformBuffers) {
  391. // Ubo replacement
  392. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  393. return p1 + "{X}";
  394. });
  395. }
  396. includeContent = includeContent.replace(/\{X\}/g, indexString);
  397. }
  398. }
  399. // Replace
  400. returnValue = returnValue.replace(match[0], includeContent);
  401. }
  402. else {
  403. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  404. _this._engine._loadFileAsync(includeShaderUrl)
  405. .then(function (fileContent) {
  406. Effect.IncludesShadersStore[includeFile] = fileContent;
  407. return _this._processIncludesAsync(returnValue);
  408. })
  409. .then(function (returnValue) {
  410. resolve(returnValue);
  411. });
  412. return;
  413. }
  414. match = regex.exec(sourceCode);
  415. }
  416. resolve(returnValue);
  417. });
  418. };
  419. Effect.prototype._processPrecision = function (source) {
  420. if (source.indexOf("precision highp float") === -1) {
  421. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  422. source = "precision mediump float;\n" + source;
  423. }
  424. else {
  425. source = "precision highp float;\n" + source;
  426. }
  427. }
  428. else {
  429. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  430. source = source.replace("precision highp float", "precision mediump float");
  431. }
  432. }
  433. return source;
  434. };
  435. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  436. var _this = this;
  437. this._isReady = false;
  438. this._vertexSourceCodeOverride = vertexSourceCode;
  439. this._fragmentSourceCodeOverride = fragmentSourceCode;
  440. this.onError = function (effect, error) {
  441. if (onError) {
  442. onError(error);
  443. }
  444. };
  445. this.onCompiled = function () {
  446. var scenes = _this.getEngine().scenes;
  447. for (var i = 0; i < scenes.length; i++) {
  448. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  449. }
  450. if (onCompiled) {
  451. onCompiled(_this._program);
  452. }
  453. };
  454. this._fallbacks = null;
  455. this._prepareEffect();
  456. };
  457. Effect.prototype.getSpecificUniformLocations = function (names) {
  458. var engine = this._engine;
  459. return engine.getUniforms(this._program, names);
  460. };
  461. Effect.prototype._prepareEffect = function () {
  462. var attributesNames = this._attributesNames;
  463. var defines = this.defines;
  464. var fallbacks = this._fallbacks;
  465. this._valueCache = {};
  466. var previousProgram = this._program;
  467. try {
  468. var engine = this._engine;
  469. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  470. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  471. }
  472. else {
  473. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  474. }
  475. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  476. if (engine.supportsUniformBuffers) {
  477. for (var name in this._uniformBuffersNames) {
  478. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  479. }
  480. }
  481. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  482. this._attributes = engine.getAttributes(this._program, attributesNames);
  483. var index;
  484. for (index = 0; index < this._samplers.length; index++) {
  485. var sampler = this.getUniform(this._samplers[index]);
  486. if (sampler == null) {
  487. this._samplers.splice(index, 1);
  488. index--;
  489. }
  490. }
  491. engine.bindSamplers(this);
  492. this._compilationError = "";
  493. this._isReady = true;
  494. if (this.onCompiled) {
  495. this.onCompiled(this);
  496. }
  497. this.onCompileObservable.notifyObservers(this);
  498. this.onCompileObservable.clear();
  499. // Unbind mesh reference in fallbacks
  500. if (this._fallbacks) {
  501. this._fallbacks.unBindMesh();
  502. }
  503. if (previousProgram) {
  504. this.getEngine()._deleteProgram(previousProgram);
  505. }
  506. }
  507. catch (e) {
  508. this._compilationError = e.message;
  509. // Let's go through fallbacks then
  510. BABYLON.Tools.Error("Unable to compile effect:");
  511. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  512. return " " + uniform;
  513. }));
  514. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  515. return " " + attribute;
  516. }));
  517. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  518. BABYLON.Tools.Error("Error: " + this._compilationError);
  519. if (previousProgram) {
  520. this._program = previousProgram;
  521. this._isReady = true;
  522. if (this.onError) {
  523. this.onError(this, this._compilationError);
  524. }
  525. this.onErrorObservable.notifyObservers(this);
  526. }
  527. if (fallbacks && fallbacks.isMoreFallbacks) {
  528. BABYLON.Tools.Error("Trying next fallback.");
  529. this.defines = fallbacks.reduce(this.defines);
  530. this._prepareEffect();
  531. }
  532. else {
  533. if (this.onError) {
  534. this.onError(this, this._compilationError);
  535. }
  536. this.onErrorObservable.notifyObservers(this);
  537. this.onErrorObservable.clear();
  538. // Unbind mesh reference in fallbacks
  539. if (this._fallbacks) {
  540. this._fallbacks.unBindMesh();
  541. }
  542. }
  543. }
  544. };
  545. Object.defineProperty(Effect.prototype, "isSupported", {
  546. get: function () {
  547. return this._compilationError === "";
  548. },
  549. enumerable: true,
  550. configurable: true
  551. });
  552. Effect.prototype._bindTexture = function (channel, texture) {
  553. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  554. };
  555. Effect.prototype.setTexture = function (channel, texture) {
  556. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  557. };
  558. Effect.prototype.setTextureArray = function (channel, textures) {
  559. if (this._samplers.indexOf(channel + "Ex") === -1) {
  560. var initialPos = this._samplers.indexOf(channel);
  561. for (var index = 1; index < textures.length; index++) {
  562. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  563. }
  564. }
  565. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  566. };
  567. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  568. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  569. };
  570. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  571. var cache = this._valueCache[uniformName];
  572. var flag = matrix.updateFlag;
  573. if (cache !== undefined && cache === flag) {
  574. return false;
  575. }
  576. this._valueCache[uniformName] = flag;
  577. return true;
  578. };
  579. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  580. var cache = this._valueCache[uniformName];
  581. if (!cache) {
  582. cache = [x, y];
  583. this._valueCache[uniformName] = cache;
  584. return true;
  585. }
  586. var changed = false;
  587. if (cache[0] !== x) {
  588. cache[0] = x;
  589. changed = true;
  590. }
  591. if (cache[1] !== y) {
  592. cache[1] = y;
  593. changed = true;
  594. }
  595. return changed;
  596. };
  597. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  598. var cache = this._valueCache[uniformName];
  599. if (!cache) {
  600. cache = [x, y, z];
  601. this._valueCache[uniformName] = cache;
  602. return true;
  603. }
  604. var changed = false;
  605. if (cache[0] !== x) {
  606. cache[0] = x;
  607. changed = true;
  608. }
  609. if (cache[1] !== y) {
  610. cache[1] = y;
  611. changed = true;
  612. }
  613. if (cache[2] !== z) {
  614. cache[2] = z;
  615. changed = true;
  616. }
  617. return changed;
  618. };
  619. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  620. var cache = this._valueCache[uniformName];
  621. if (!cache) {
  622. cache = [x, y, z, w];
  623. this._valueCache[uniformName] = cache;
  624. return true;
  625. }
  626. var changed = false;
  627. if (cache[0] !== x) {
  628. cache[0] = x;
  629. changed = true;
  630. }
  631. if (cache[1] !== y) {
  632. cache[1] = y;
  633. changed = true;
  634. }
  635. if (cache[2] !== z) {
  636. cache[2] = z;
  637. changed = true;
  638. }
  639. if (cache[3] !== w) {
  640. cache[3] = w;
  641. changed = true;
  642. }
  643. return changed;
  644. };
  645. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  646. var bufferName = this._uniformBuffersNames[name];
  647. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  648. return;
  649. }
  650. Effect._baseCache[bufferName] = buffer;
  651. this._engine.bindUniformBufferBase(buffer, bufferName);
  652. };
  653. Effect.prototype.bindUniformBlock = function (blockName, index) {
  654. this._engine.bindUniformBlock(this._program, blockName, index);
  655. };
  656. Effect.prototype.setInt = function (uniformName, value) {
  657. var cache = this._valueCache[uniformName];
  658. if (cache !== undefined && cache === value)
  659. return this;
  660. this._valueCache[uniformName] = value;
  661. this._engine.setInt(this.getUniform(uniformName), value);
  662. return this;
  663. };
  664. Effect.prototype.setIntArray = function (uniformName, array) {
  665. this._valueCache[uniformName] = null;
  666. this._engine.setIntArray(this.getUniform(uniformName), array);
  667. return this;
  668. };
  669. Effect.prototype.setIntArray2 = function (uniformName, array) {
  670. this._valueCache[uniformName] = null;
  671. this._engine.setIntArray2(this.getUniform(uniformName), array);
  672. return this;
  673. };
  674. Effect.prototype.setIntArray3 = function (uniformName, array) {
  675. this._valueCache[uniformName] = null;
  676. this._engine.setIntArray3(this.getUniform(uniformName), array);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray4 = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray4(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setFloatArray = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setFloatArray(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setArray = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setArray(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setArray2 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setArray2(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setArray3 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setArray3(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray4 = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray4(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setMatrices = function (uniformName, matrices) {
  725. if (!matrices) {
  726. return this;
  727. }
  728. this._valueCache[uniformName] = null;
  729. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  730. return this;
  731. };
  732. Effect.prototype.setMatrix = function (uniformName, matrix) {
  733. if (this._cacheMatrix(uniformName, matrix)) {
  734. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  735. }
  736. return this;
  737. };
  738. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  739. this._valueCache[uniformName] = null;
  740. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  741. return this;
  742. };
  743. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  744. this._valueCache[uniformName] = null;
  745. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  746. return this;
  747. };
  748. Effect.prototype.setFloat = function (uniformName, value) {
  749. var cache = this._valueCache[uniformName];
  750. if (cache !== undefined && cache === value)
  751. return this;
  752. this._valueCache[uniformName] = value;
  753. this._engine.setFloat(this.getUniform(uniformName), value);
  754. return this;
  755. };
  756. Effect.prototype.setBool = function (uniformName, bool) {
  757. var cache = this._valueCache[uniformName];
  758. if (cache !== undefined && cache === bool)
  759. return this;
  760. this._valueCache[uniformName] = bool;
  761. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  762. return this;
  763. };
  764. Effect.prototype.setVector2 = function (uniformName, vector2) {
  765. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  766. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  767. }
  768. return this;
  769. };
  770. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  771. if (this._cacheFloat2(uniformName, x, y)) {
  772. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  773. }
  774. return this;
  775. };
  776. Effect.prototype.setVector3 = function (uniformName, vector3) {
  777. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  778. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  783. if (this._cacheFloat3(uniformName, x, y, z)) {
  784. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector4 = function (uniformName, vector4) {
  789. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  790. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  795. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  796. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setColor3 = function (uniformName, color3) {
  801. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  802. this._engine.setColor3(this.getUniform(uniformName), color3);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  807. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  808. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  809. }
  810. return this;
  811. };
  812. Effect.ResetCache = function () {
  813. Effect._baseCache = {};
  814. };
  815. Effect._uniqueIdSeed = 0;
  816. Effect._baseCache = {};
  817. // Statics
  818. Effect.ShadersStore = {};
  819. Effect.IncludesShadersStore = {};
  820. return Effect;
  821. }());
  822. BABYLON.Effect = Effect;
  823. })(BABYLON || (BABYLON = {}));
  824. //# sourceMappingURL=babylon.effect.js.map
  825. //# sourceMappingURL=babylon.types.js.map
  826. var BABYLON;
  827. (function (BABYLON) {
  828. var KeyboardEventTypes = /** @class */ (function () {
  829. function KeyboardEventTypes() {
  830. }
  831. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  832. get: function () {
  833. return KeyboardEventTypes._KEYDOWN;
  834. },
  835. enumerable: true,
  836. configurable: true
  837. });
  838. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  839. get: function () {
  840. return KeyboardEventTypes._KEYUP;
  841. },
  842. enumerable: true,
  843. configurable: true
  844. });
  845. KeyboardEventTypes._KEYDOWN = 0x01;
  846. KeyboardEventTypes._KEYUP = 0x02;
  847. return KeyboardEventTypes;
  848. }());
  849. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  850. var KeyboardInfo = /** @class */ (function () {
  851. function KeyboardInfo(type, event) {
  852. this.type = type;
  853. this.event = event;
  854. }
  855. return KeyboardInfo;
  856. }());
  857. BABYLON.KeyboardInfo = KeyboardInfo;
  858. /**
  859. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  860. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  861. */
  862. var KeyboardInfoPre = /** @class */ (function (_super) {
  863. __extends(KeyboardInfoPre, _super);
  864. function KeyboardInfoPre(type, event) {
  865. var _this = _super.call(this, type, event) || this;
  866. _this.skipOnPointerObservable = false;
  867. return _this;
  868. }
  869. return KeyboardInfoPre;
  870. }(KeyboardInfo));
  871. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.keyboardEvents.js.map
  874. var BABYLON;
  875. (function (BABYLON) {
  876. var PointerEventTypes = /** @class */ (function () {
  877. function PointerEventTypes() {
  878. }
  879. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  880. get: function () {
  881. return PointerEventTypes._POINTERDOWN;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  887. get: function () {
  888. return PointerEventTypes._POINTERUP;
  889. },
  890. enumerable: true,
  891. configurable: true
  892. });
  893. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  894. get: function () {
  895. return PointerEventTypes._POINTERMOVE;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  901. get: function () {
  902. return PointerEventTypes._POINTERWHEEL;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  908. get: function () {
  909. return PointerEventTypes._POINTERPICK;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  915. get: function () {
  916. return PointerEventTypes._POINTERTAP;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  922. get: function () {
  923. return PointerEventTypes._POINTERDOUBLETAP;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. PointerEventTypes._POINTERDOWN = 0x01;
  929. PointerEventTypes._POINTERUP = 0x02;
  930. PointerEventTypes._POINTERMOVE = 0x04;
  931. PointerEventTypes._POINTERWHEEL = 0x08;
  932. PointerEventTypes._POINTERPICK = 0x10;
  933. PointerEventTypes._POINTERTAP = 0x20;
  934. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  935. return PointerEventTypes;
  936. }());
  937. BABYLON.PointerEventTypes = PointerEventTypes;
  938. var PointerInfoBase = /** @class */ (function () {
  939. function PointerInfoBase(type, event) {
  940. this.type = type;
  941. this.event = event;
  942. }
  943. return PointerInfoBase;
  944. }());
  945. BABYLON.PointerInfoBase = PointerInfoBase;
  946. /**
  947. * This class is used to store pointer related info for the onPrePointerObservable event.
  948. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  949. */
  950. var PointerInfoPre = /** @class */ (function (_super) {
  951. __extends(PointerInfoPre, _super);
  952. function PointerInfoPre(type, event, localX, localY) {
  953. var _this = _super.call(this, type, event) || this;
  954. _this.skipOnPointerObservable = false;
  955. _this.localPosition = new BABYLON.Vector2(localX, localY);
  956. return _this;
  957. }
  958. return PointerInfoPre;
  959. }(PointerInfoBase));
  960. BABYLON.PointerInfoPre = PointerInfoPre;
  961. /**
  962. * This type contains all the data related to a pointer event in Babylon.js.
  963. * 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.
  964. */
  965. var PointerInfo = /** @class */ (function (_super) {
  966. __extends(PointerInfo, _super);
  967. function PointerInfo(type, event, pickInfo) {
  968. var _this = _super.call(this, type, event) || this;
  969. _this.pickInfo = pickInfo;
  970. return _this;
  971. }
  972. return PointerInfo;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfo = PointerInfo;
  975. })(BABYLON || (BABYLON = {}));
  976. //# sourceMappingURL=babylon.pointerEvents.js.map
  977. var BABYLON;
  978. (function (BABYLON) {
  979. BABYLON.ToGammaSpace = 1 / 2.2;
  980. BABYLON.ToLinearSpace = 2.2;
  981. BABYLON.Epsilon = 0.001;
  982. /**
  983. * Class used to hold a RBG color
  984. */
  985. var Color3 = /** @class */ (function () {
  986. /**
  987. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  988. * @param r defines the red component (between 0 and 1, default is 0)
  989. * @param g defines the green component (between 0 and 1, default is 0)
  990. * @param b defines the blue component (between 0 and 1, default is 0)
  991. */
  992. function Color3(
  993. /**
  994. * Defines the red component (between 0 and 1, default is 0)
  995. */
  996. r,
  997. /**
  998. * Defines the green component (between 0 and 1, default is 0)
  999. */
  1000. g,
  1001. /**
  1002. * Defines the blue component (between 0 and 1, default is 0)
  1003. */
  1004. b) {
  1005. if (r === void 0) { r = 0; }
  1006. if (g === void 0) { g = 0; }
  1007. if (b === void 0) { b = 0; }
  1008. this.r = r;
  1009. this.g = g;
  1010. this.b = b;
  1011. }
  1012. /**
  1013. * Creates a string with the Color3 current values
  1014. * @returns the string representation of the Color3 object
  1015. */
  1016. Color3.prototype.toString = function () {
  1017. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Color3"
  1021. * @returns "Color3"
  1022. */
  1023. Color3.prototype.getClassName = function () {
  1024. return "Color3";
  1025. };
  1026. /**
  1027. * Compute the Color3 hash code
  1028. * @returns an unique number that can be used to hash Color3 objects
  1029. */
  1030. Color3.prototype.getHashCode = function () {
  1031. var hash = this.r || 0;
  1032. hash = (hash * 397) ^ (this.g || 0);
  1033. hash = (hash * 397) ^ (this.b || 0);
  1034. return hash;
  1035. };
  1036. // Operators
  1037. /**
  1038. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1039. * @param array defines the array where to store the r,g,b components
  1040. * @param index defines an optional index in the target array to define where to start storing values
  1041. * @returns the current Color3 object
  1042. */
  1043. Color3.prototype.toArray = function (array, index) {
  1044. if (index === undefined) {
  1045. index = 0;
  1046. }
  1047. array[index] = this.r;
  1048. array[index + 1] = this.g;
  1049. array[index + 2] = this.b;
  1050. return this;
  1051. };
  1052. /**
  1053. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1054. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1055. * @returns a new {BABYLON.Color4} object
  1056. */
  1057. Color3.prototype.toColor4 = function (alpha) {
  1058. if (alpha === void 0) { alpha = 1; }
  1059. return new Color4(this.r, this.g, this.b, alpha);
  1060. };
  1061. /**
  1062. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1063. * @returns the new array
  1064. */
  1065. Color3.prototype.asArray = function () {
  1066. var result = new Array();
  1067. this.toArray(result, 0);
  1068. return result;
  1069. };
  1070. /**
  1071. * Returns the luminance value
  1072. * @returns a float value
  1073. */
  1074. Color3.prototype.toLuminance = function () {
  1075. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1076. };
  1077. /**
  1078. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1079. * @param otherColor defines the second operand
  1080. * @returns the new Color3 object
  1081. */
  1082. Color3.prototype.multiply = function (otherColor) {
  1083. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1084. };
  1085. /**
  1086. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1087. * @param otherColor defines the second operand
  1088. * @param result defines the Color3 object where to store the result
  1089. * @returns the current Color3
  1090. */
  1091. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1092. result.r = this.r * otherColor.r;
  1093. result.g = this.g * otherColor.g;
  1094. result.b = this.b * otherColor.b;
  1095. return this;
  1096. };
  1097. /**
  1098. * Determines equality between Color3 objects
  1099. * @param otherColor defines the second operand
  1100. * @returns true if the rgb values are equal to the passed ones
  1101. */
  1102. Color3.prototype.equals = function (otherColor) {
  1103. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1104. };
  1105. /**
  1106. * Determines equality between the current Color3 object and a set of r,b,g values
  1107. * @param r defines the red component to check
  1108. * @param g defines the green component to check
  1109. * @param b defines the blue component to check
  1110. * @returns true if the rgb values are equal to the passed ones
  1111. */
  1112. Color3.prototype.equalsFloats = function (r, g, b) {
  1113. return this.r === r && this.g === g && this.b === b;
  1114. };
  1115. /**
  1116. * Multiplies in place each rgb value by scale
  1117. * @param scale defines the scaling factor
  1118. * @returns the updated Color3.
  1119. */
  1120. Color3.prototype.scale = function (scale) {
  1121. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1122. };
  1123. /**
  1124. * Multiplies the rgb values by scale and stores the result into "result"
  1125. * @param scale defines the scaling factor
  1126. * @param result defines the Color3 object where to store the result
  1127. * @returns the unmodified current Color3.
  1128. */
  1129. Color3.prototype.scaleToRef = function (scale, result) {
  1130. result.r = this.r * scale;
  1131. result.g = this.g * scale;
  1132. result.b = this.b * scale;
  1133. return this;
  1134. };
  1135. /**
  1136. * Clamps the rgb values by the min and max values and stores the result into "result"
  1137. * @param min defines minimum clamping value (default is 0)
  1138. * @param max defines maximum clamping value (default is 1)
  1139. * @param result defines color to store the result into
  1140. * @returns the original Color3
  1141. */
  1142. Color3.prototype.clampToRef = function (min, max, result) {
  1143. if (min === void 0) { min = 0; }
  1144. if (max === void 0) { max = 1; }
  1145. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1146. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1147. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1148. return this;
  1149. };
  1150. /**
  1151. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1152. * @param otherColor defines the second operand
  1153. * @returns the new Color3
  1154. */
  1155. Color3.prototype.add = function (otherColor) {
  1156. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1157. };
  1158. /**
  1159. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1160. * @param otherColor defines the second operand
  1161. * @param result defines Color3 object to store the result into
  1162. * @returns the unmodified current Color3
  1163. */
  1164. Color3.prototype.addToRef = function (otherColor, result) {
  1165. result.r = this.r + otherColor.r;
  1166. result.g = this.g + otherColor.g;
  1167. result.b = this.b + otherColor.b;
  1168. return this;
  1169. };
  1170. /**
  1171. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1172. * @param otherColor defines the second operand
  1173. * @returns the new Color3
  1174. */
  1175. Color3.prototype.subtract = function (otherColor) {
  1176. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1177. };
  1178. /**
  1179. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1180. * @param otherColor defines the second operand
  1181. * @param result defines Color3 object to store the result into
  1182. * @returns the unmodified current Color3
  1183. */
  1184. Color3.prototype.subtractToRef = function (otherColor, result) {
  1185. result.r = this.r - otherColor.r;
  1186. result.g = this.g - otherColor.g;
  1187. result.b = this.b - otherColor.b;
  1188. return this;
  1189. };
  1190. /**
  1191. * Copy the current object
  1192. * @returns a new Color3 copied the current one
  1193. */
  1194. Color3.prototype.clone = function () {
  1195. return new Color3(this.r, this.g, this.b);
  1196. };
  1197. /**
  1198. * Copies the rgb values from the source in the current Color3
  1199. * @param source defines the source Color3 object
  1200. * @returns the updated Color3 object
  1201. */
  1202. Color3.prototype.copyFrom = function (source) {
  1203. this.r = source.r;
  1204. this.g = source.g;
  1205. this.b = source.b;
  1206. return this;
  1207. };
  1208. /**
  1209. * Updates the Color3 rgb values from the passed floats
  1210. * @param r defines the red component to read from
  1211. * @param g defines the green component to read from
  1212. * @param b defines the blue component to read from
  1213. * @returns the current Color3 object
  1214. */
  1215. Color3.prototype.copyFromFloats = function (r, g, b) {
  1216. this.r = r;
  1217. this.g = g;
  1218. this.b = b;
  1219. return this;
  1220. };
  1221. /**
  1222. * Updates the Color3 rgb values from the passed floats
  1223. * @param r defines the red component to read from
  1224. * @param g defines the green component to read from
  1225. * @param b defines the blue component to read from
  1226. * @returns the current Color3 object
  1227. */
  1228. Color3.prototype.set = function (r, g, b) {
  1229. return this.copyFromFloats(r, g, b);
  1230. };
  1231. /**
  1232. * Compute the Color3 hexadecimal code as a string
  1233. * @returns a string containing the hexadecimal representation of the Color3 object
  1234. */
  1235. Color3.prototype.toHexString = function () {
  1236. var intR = (this.r * 255) | 0;
  1237. var intG = (this.g * 255) | 0;
  1238. var intB = (this.b * 255) | 0;
  1239. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1240. };
  1241. /**
  1242. * Computes a new Color3 converted from the current one to linear space
  1243. * @returns a new Color3 object
  1244. */
  1245. Color3.prototype.toLinearSpace = function () {
  1246. var convertedColor = new Color3();
  1247. this.toLinearSpaceToRef(convertedColor);
  1248. return convertedColor;
  1249. };
  1250. /**
  1251. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1252. * @param convertedColor defines the Color3 object where to store the linear space version
  1253. * @returns the unmodified Color3
  1254. */
  1255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1259. return this;
  1260. };
  1261. /**
  1262. * Computes a new Color3 converted from the current one to gamma space
  1263. * @returns a new Color3 object
  1264. */
  1265. Color3.prototype.toGammaSpace = function () {
  1266. var convertedColor = new Color3();
  1267. this.toGammaSpaceToRef(convertedColor);
  1268. return convertedColor;
  1269. };
  1270. /**
  1271. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1272. * @param convertedColor defines the Color3 object where to store the gamma space version
  1273. * @returns the unmodified Color3
  1274. */
  1275. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1276. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1277. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1278. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1279. return this;
  1280. };
  1281. // Statics
  1282. /**
  1283. * Creates a new Color3 from the string containing valid hexadecimal values
  1284. * @param hex defines a string containing valid hexadecimal values
  1285. * @returns a new Color3 object
  1286. */
  1287. Color3.FromHexString = function (hex) {
  1288. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1289. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1290. return new Color3(0, 0, 0);
  1291. }
  1292. var r = parseInt(hex.substring(1, 3), 16);
  1293. var g = parseInt(hex.substring(3, 5), 16);
  1294. var b = parseInt(hex.substring(5, 7), 16);
  1295. return Color3.FromInts(r, g, b);
  1296. };
  1297. /**
  1298. * Creates a new Vector3 from the starting index of the passed array
  1299. * @param array defines the source array
  1300. * @param offset defines an offset in the source array
  1301. * @returns a new Color3 object
  1302. */
  1303. Color3.FromArray = function (array, offset) {
  1304. if (offset === void 0) { offset = 0; }
  1305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1306. };
  1307. /**
  1308. * Creates a new Color3 from integer values (< 256)
  1309. * @param r defines the red component to read from (value between 0 and 255)
  1310. * @param g defines the green component to read from (value between 0 and 255)
  1311. * @param b defines the blue component to read from (value between 0 and 255)
  1312. * @returns a new Color3 object
  1313. */
  1314. Color3.FromInts = function (r, g, b) {
  1315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1316. };
  1317. /**
  1318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1319. * @param start defines the start Color3 value
  1320. * @param end defines the end Color3 value
  1321. * @param amount defines the gradient value between start and end
  1322. * @returns a new Color3 object
  1323. */
  1324. Color3.Lerp = function (start, end, amount) {
  1325. var r = start.r + ((end.r - start.r) * amount);
  1326. var g = start.g + ((end.g - start.g) * amount);
  1327. var b = start.b + ((end.b - start.b) * amount);
  1328. return new Color3(r, g, b);
  1329. };
  1330. /**
  1331. * Returns a Color3 value containing a red color
  1332. * @returns a new Color3 object
  1333. */
  1334. Color3.Red = function () { return new Color3(1, 0, 0); };
  1335. /**
  1336. * Returns a Color3 value containing a green color
  1337. * @returns a new Color3 object
  1338. */
  1339. Color3.Green = function () { return new Color3(0, 1, 0); };
  1340. /**
  1341. * Returns a Color3 value containing a blue color
  1342. * @returns a new Color3 object
  1343. */
  1344. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1345. /**
  1346. * Returns a Color3 value containing a black color
  1347. * @returns a new Color3 object
  1348. */
  1349. Color3.Black = function () { return new Color3(0, 0, 0); };
  1350. /**
  1351. * Returns a Color3 value containing a white color
  1352. * @returns a new Color3 object
  1353. */
  1354. Color3.White = function () { return new Color3(1, 1, 1); };
  1355. /**
  1356. * Returns a Color3 value containing a purple color
  1357. * @returns a new Color3 object
  1358. */
  1359. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1360. /**
  1361. * Returns a Color3 value containing a magenta color
  1362. * @returns a new Color3 object
  1363. */
  1364. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1365. /**
  1366. * Returns a Color3 value containing a yellow color
  1367. * @returns a new Color3 object
  1368. */
  1369. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1370. /**
  1371. * Returns a Color3 value containing a gray color
  1372. * @returns a new Color3 object
  1373. */
  1374. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1375. /**
  1376. * Returns a Color3 value containing a teal color
  1377. * @returns a new Color3 object
  1378. */
  1379. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1380. /**
  1381. * Returns a Color3 value containing a random color
  1382. * @returns a new Color3 object
  1383. */
  1384. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1385. return Color3;
  1386. }());
  1387. BABYLON.Color3 = Color3;
  1388. /**
  1389. * Class used to hold a RBGA color
  1390. */
  1391. var Color4 = /** @class */ (function () {
  1392. /**
  1393. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1394. * @param r defines the red component (between 0 and 1, default is 0)
  1395. * @param g defines the green component (between 0 and 1, default is 0)
  1396. * @param b defines the blue component (between 0 and 1, default is 0)
  1397. * @param a defines the alpha component (between 0 and 1, default is 1)
  1398. */
  1399. function Color4(
  1400. /**
  1401. * Defines the red component (between 0 and 1, default is 0)
  1402. */
  1403. r,
  1404. /**
  1405. * Defines the green component (between 0 and 1, default is 0)
  1406. */
  1407. g,
  1408. /**
  1409. * Defines the blue component (between 0 and 1, default is 0)
  1410. */
  1411. b,
  1412. /**
  1413. * Defines the alpha component (between 0 and 1, default is 1)
  1414. */
  1415. a) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. if (a === void 0) { a = 1; }
  1420. this.r = r;
  1421. this.g = g;
  1422. this.b = b;
  1423. this.a = a;
  1424. }
  1425. // Operators
  1426. /**
  1427. * Adds in place the passed Color4 values to the current Color4 object
  1428. * @param right defines the second operand
  1429. * @returns the current updated Color4 object
  1430. */
  1431. Color4.prototype.addInPlace = function (right) {
  1432. this.r += right.r;
  1433. this.g += right.g;
  1434. this.b += right.b;
  1435. this.a += right.a;
  1436. return this;
  1437. };
  1438. /**
  1439. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1440. * @returns the new array
  1441. */
  1442. Color4.prototype.asArray = function () {
  1443. var result = new Array();
  1444. this.toArray(result, 0);
  1445. return result;
  1446. };
  1447. /**
  1448. * Stores from the starting index in the passed array the Color4 successive values
  1449. * @param array defines the array where to store the r,g,b components
  1450. * @param index defines an optional index in the target array to define where to start storing values
  1451. * @returns the current Color4 object
  1452. */
  1453. Color4.prototype.toArray = function (array, index) {
  1454. if (index === undefined) {
  1455. index = 0;
  1456. }
  1457. array[index] = this.r;
  1458. array[index + 1] = this.g;
  1459. array[index + 2] = this.b;
  1460. array[index + 3] = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1465. * @param right defines the second operand
  1466. * @returns a new Color4 object
  1467. */
  1468. Color4.prototype.add = function (right) {
  1469. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1470. };
  1471. /**
  1472. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1473. * @param right defines the second operand
  1474. * @returns a new Color4 object
  1475. */
  1476. Color4.prototype.subtract = function (right) {
  1477. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1478. };
  1479. /**
  1480. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1481. * @param right defines the second operand
  1482. * @param result defines the Color4 object where to store the result
  1483. * @returns the current Color4 object
  1484. */
  1485. Color4.prototype.subtractToRef = function (right, result) {
  1486. result.r = this.r - right.r;
  1487. result.g = this.g - right.g;
  1488. result.b = this.b - right.b;
  1489. result.a = this.a - right.a;
  1490. return this;
  1491. };
  1492. /**
  1493. * Creates a new Color4 with the current Color4 values multiplied by scale
  1494. * @param scale defines the scaling factor to apply
  1495. * @returns a new Color4 object
  1496. */
  1497. Color4.prototype.scale = function (scale) {
  1498. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1499. };
  1500. /**
  1501. * Multiplies the current Color4 values by scale and stores the result in "result"
  1502. * @param scale defines the scaling factor to apply
  1503. * @param result defines the Color4 object where to store the result
  1504. * @returns the current Color4.
  1505. */
  1506. Color4.prototype.scaleToRef = function (scale, result) {
  1507. result.r = this.r * scale;
  1508. result.g = this.g * scale;
  1509. result.b = this.b * scale;
  1510. result.a = this.a * scale;
  1511. return this;
  1512. };
  1513. /**
  1514. * Clamps the rgb values by the min and max values and stores the result into "result"
  1515. * @param min defines minimum clamping value (default is 0)
  1516. * @param max defines maximum clamping value (default is 1)
  1517. * @param result defines color to store the result into.
  1518. * @returns the cuurent Color4
  1519. */
  1520. Color4.prototype.clampToRef = function (min, max, result) {
  1521. if (min === void 0) { min = 0; }
  1522. if (max === void 0) { max = 1; }
  1523. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1524. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1525. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1526. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1527. return this;
  1528. };
  1529. /**
  1530. * Multipy an Color4 value by another and return a new Color4 object
  1531. * @param color defines the Color4 value to multiply by
  1532. * @returns a new Color4 object
  1533. */
  1534. Color4.prototype.multiply = function (color) {
  1535. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1536. };
  1537. /**
  1538. * Multipy a Color4 value by another and push the result in a reference value
  1539. * @param color defines the Color4 value to multiply by
  1540. * @param result defines the Color4 to fill the result in
  1541. * @returns the result Color4
  1542. */
  1543. Color4.prototype.multiplyToRef = function (color, result) {
  1544. result.r = this.r * color.r;
  1545. result.g = this.g * color.g;
  1546. result.b = this.b * color.b;
  1547. result.a = this.a * color.a;
  1548. return result;
  1549. };
  1550. /**
  1551. * Creates a string with the Color4 current values
  1552. * @returns the string representation of the Color4 object
  1553. */
  1554. Color4.prototype.toString = function () {
  1555. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1556. };
  1557. /**
  1558. * Returns the string "Color4"
  1559. * @returns "Color4"
  1560. */
  1561. Color4.prototype.getClassName = function () {
  1562. return "Color4";
  1563. };
  1564. /**
  1565. * Compute the Color4 hash code
  1566. * @returns an unique number that can be used to hash Color4 objects
  1567. */
  1568. Color4.prototype.getHashCode = function () {
  1569. var hash = this.r || 0;
  1570. hash = (hash * 397) ^ (this.g || 0);
  1571. hash = (hash * 397) ^ (this.b || 0);
  1572. hash = (hash * 397) ^ (this.a || 0);
  1573. return hash;
  1574. };
  1575. /**
  1576. * Creates a new Color4 copied from the current one
  1577. * @returns a new Color4 object
  1578. */
  1579. Color4.prototype.clone = function () {
  1580. return new Color4(this.r, this.g, this.b, this.a);
  1581. };
  1582. /**
  1583. * Copies the passed Color4 values into the current one
  1584. * @param source defines the source Color4 object
  1585. * @returns the current updated Color4 object
  1586. */
  1587. Color4.prototype.copyFrom = function (source) {
  1588. this.r = source.r;
  1589. this.g = source.g;
  1590. this.b = source.b;
  1591. this.a = source.a;
  1592. return this;
  1593. };
  1594. /**
  1595. * Copies the passed float values into the current one
  1596. * @param r defines the red component to read from
  1597. * @param g defines the green component to read from
  1598. * @param b defines the blue component to read from
  1599. * @param a defines the alpha component to read from
  1600. * @returns the current updated Color4 object
  1601. */
  1602. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1603. this.r = r;
  1604. this.g = g;
  1605. this.b = b;
  1606. this.a = a;
  1607. return this;
  1608. };
  1609. /**
  1610. * Copies the passed float values into the current one
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @param a defines the alpha component to read from
  1615. * @returns the current updated Color4 object
  1616. */
  1617. Color4.prototype.set = function (r, g, b, a) {
  1618. return this.copyFromFloats(r, g, b, a);
  1619. };
  1620. /**
  1621. * Compute the Color4 hexadecimal code as a string
  1622. * @returns a string containing the hexadecimal representation of the Color4 object
  1623. */
  1624. Color4.prototype.toHexString = function () {
  1625. var intR = (this.r * 255) | 0;
  1626. var intG = (this.g * 255) | 0;
  1627. var intB = (this.b * 255) | 0;
  1628. var intA = (this.a * 255) | 0;
  1629. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1630. };
  1631. /**
  1632. * Computes a new Color4 converted from the current one to linear space
  1633. * @returns a new Color4 object
  1634. */
  1635. Color4.prototype.toLinearSpace = function () {
  1636. var convertedColor = new Color4();
  1637. this.toLinearSpaceToRef(convertedColor);
  1638. return convertedColor;
  1639. };
  1640. /**
  1641. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1642. * @param convertedColor defines the Color4 object where to store the linear space version
  1643. * @returns the unmodified Color4
  1644. */
  1645. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1646. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1647. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1648. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1649. convertedColor.a = this.a;
  1650. return this;
  1651. };
  1652. /**
  1653. * Computes a new Color4 converted from the current one to gamma space
  1654. * @returns a new Color4 object
  1655. */
  1656. Color4.prototype.toGammaSpace = function () {
  1657. var convertedColor = new Color4();
  1658. this.toGammaSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color4 object where to store the gamma space version
  1664. * @returns the unmodified Color4
  1665. */
  1666. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1670. convertedColor.a = this.a;
  1671. return this;
  1672. };
  1673. // Statics
  1674. /**
  1675. * Creates a new Color4 from the string containing valid hexadecimal values
  1676. * @param hex defines a string containing valid hexadecimal values
  1677. * @returns a new Color4 object
  1678. */
  1679. Color4.FromHexString = function (hex) {
  1680. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1681. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1682. return new Color4(0.0, 0.0, 0.0, 0.0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. var a = parseInt(hex.substring(7, 9), 16);
  1688. return Color4.FromInts(r, g, b, a);
  1689. };
  1690. /**
  1691. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1692. * @param left defines the start value
  1693. * @param right defines the end value
  1694. * @param amount defines the gradient factor
  1695. * @returns a new Color4 object
  1696. */
  1697. Color4.Lerp = function (left, right, amount) {
  1698. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1699. Color4.LerpToRef(left, right, amount, result);
  1700. return result;
  1701. };
  1702. /**
  1703. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1704. * @param left defines the start value
  1705. * @param right defines the end value
  1706. * @param amount defines the gradient factor
  1707. * @param result defines the Color4 object where to store data
  1708. */
  1709. Color4.LerpToRef = function (left, right, amount, result) {
  1710. result.r = left.r + (right.r - left.r) * amount;
  1711. result.g = left.g + (right.g - left.g) * amount;
  1712. result.b = left.b + (right.b - left.b) * amount;
  1713. result.a = left.a + (right.a - left.a) * amount;
  1714. };
  1715. /**
  1716. * Creates a new Color4 from the starting index element of the passed array
  1717. * @param array defines the source array to read from
  1718. * @param offset defines the offset in the source array
  1719. * @returns a new Color4 object
  1720. */
  1721. Color4.FromArray = function (array, offset) {
  1722. if (offset === void 0) { offset = 0; }
  1723. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1724. };
  1725. /**
  1726. * Creates a new Color3 from integer values (< 256)
  1727. * @param r defines the red component to read from (value between 0 and 255)
  1728. * @param g defines the green component to read from (value between 0 and 255)
  1729. * @param b defines the blue component to read from (value between 0 and 255)
  1730. * @param a defines the alpha component to read from (value between 0 and 255)
  1731. * @returns a new Color3 object
  1732. */
  1733. Color4.FromInts = function (r, g, b, a) {
  1734. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1735. };
  1736. /**
  1737. * Check the content of a given array and convert it to an array containing RGBA data
  1738. * If the original array was already containing count * 4 values then it is returned directly
  1739. * @param colors defines the array to check
  1740. * @param count defines the number of RGBA data to expect
  1741. * @returns an array containing count * 4 values (RGBA)
  1742. */
  1743. Color4.CheckColors4 = function (colors, count) {
  1744. // Check if color3 was used
  1745. if (colors.length === count * 3) {
  1746. var colors4 = [];
  1747. for (var index = 0; index < colors.length; index += 3) {
  1748. var newIndex = (index / 3) * 4;
  1749. colors4[newIndex] = colors[index];
  1750. colors4[newIndex + 1] = colors[index + 1];
  1751. colors4[newIndex + 2] = colors[index + 2];
  1752. colors4[newIndex + 3] = 1.0;
  1753. }
  1754. return colors4;
  1755. }
  1756. return colors;
  1757. };
  1758. return Color4;
  1759. }());
  1760. BABYLON.Color4 = Color4;
  1761. var Vector2 = /** @class */ (function () {
  1762. /**
  1763. * Creates a new Vector2 from the passed x and y coordinates.
  1764. */
  1765. function Vector2(x, y) {
  1766. this.x = x;
  1767. this.y = y;
  1768. }
  1769. /**
  1770. * Returns a string with the Vector2 coordinates.
  1771. */
  1772. Vector2.prototype.toString = function () {
  1773. return "{X: " + this.x + " Y:" + this.y + "}";
  1774. };
  1775. /**
  1776. * Returns the string "Vector2"
  1777. */
  1778. Vector2.prototype.getClassName = function () {
  1779. return "Vector2";
  1780. };
  1781. /**
  1782. * Returns the Vector2 hash code as a number.
  1783. */
  1784. Vector2.prototype.getHashCode = function () {
  1785. var hash = this.x || 0;
  1786. hash = (hash * 397) ^ (this.y || 0);
  1787. return hash;
  1788. };
  1789. // Operators
  1790. /**
  1791. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1792. * Returns the Vector2.
  1793. */
  1794. Vector2.prototype.toArray = function (array, index) {
  1795. if (index === void 0) { index = 0; }
  1796. array[index] = this.x;
  1797. array[index + 1] = this.y;
  1798. return this;
  1799. };
  1800. /**
  1801. * Returns a new array with 2 elements : the Vector2 coordinates.
  1802. */
  1803. Vector2.prototype.asArray = function () {
  1804. var result = new Array();
  1805. this.toArray(result, 0);
  1806. return result;
  1807. };
  1808. /**
  1809. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1810. * Returns the updated Vector2.
  1811. */
  1812. Vector2.prototype.copyFrom = function (source) {
  1813. this.x = source.x;
  1814. this.y = source.y;
  1815. return this;
  1816. };
  1817. /**
  1818. * Sets the Vector2 coordinates with the passed floats.
  1819. * Returns the updated Vector2.
  1820. */
  1821. Vector2.prototype.copyFromFloats = function (x, y) {
  1822. this.x = x;
  1823. this.y = y;
  1824. return this;
  1825. };
  1826. /**
  1827. * Sets the Vector2 coordinates with the passed floats.
  1828. * Returns the updated Vector2.
  1829. */
  1830. Vector2.prototype.set = function (x, y) {
  1831. return this.copyFromFloats(x, y);
  1832. };
  1833. /**
  1834. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1835. */
  1836. Vector2.prototype.add = function (otherVector) {
  1837. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1838. };
  1839. /**
  1840. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1841. * Returns the Vector2.
  1842. */
  1843. Vector2.prototype.addToRef = function (otherVector, result) {
  1844. result.x = this.x + otherVector.x;
  1845. result.y = this.y + otherVector.y;
  1846. return this;
  1847. };
  1848. /**
  1849. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1850. * Returns the updated Vector2.
  1851. */
  1852. Vector2.prototype.addInPlace = function (otherVector) {
  1853. this.x += otherVector.x;
  1854. this.y += otherVector.y;
  1855. return this;
  1856. };
  1857. /**
  1858. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1859. */
  1860. Vector2.prototype.addVector3 = function (otherVector) {
  1861. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1862. };
  1863. /**
  1864. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1865. */
  1866. Vector2.prototype.subtract = function (otherVector) {
  1867. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1868. };
  1869. /**
  1870. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1871. * Returns the Vector2.
  1872. */
  1873. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1874. result.x = this.x - otherVector.x;
  1875. result.y = this.y - otherVector.y;
  1876. return this;
  1877. };
  1878. /**
  1879. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1880. * Returns the updated Vector2.
  1881. */
  1882. Vector2.prototype.subtractInPlace = function (otherVector) {
  1883. this.x -= otherVector.x;
  1884. this.y -= otherVector.y;
  1885. return this;
  1886. };
  1887. /**
  1888. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1889. * Returns the updated Vector2.
  1890. */
  1891. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1892. this.x *= otherVector.x;
  1893. this.y *= otherVector.y;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1898. */
  1899. Vector2.prototype.multiply = function (otherVector) {
  1900. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1901. };
  1902. /**
  1903. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1904. * Returns the Vector2.
  1905. */
  1906. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1907. result.x = this.x * otherVector.x;
  1908. result.y = this.y * otherVector.y;
  1909. return this;
  1910. };
  1911. /**
  1912. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1913. */
  1914. Vector2.prototype.multiplyByFloats = function (x, y) {
  1915. return new Vector2(this.x * x, this.y * y);
  1916. };
  1917. /**
  1918. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1919. */
  1920. Vector2.prototype.divide = function (otherVector) {
  1921. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1922. };
  1923. /**
  1924. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1925. * Returns the Vector2.
  1926. */
  1927. Vector2.prototype.divideToRef = function (otherVector, result) {
  1928. result.x = this.x / otherVector.x;
  1929. result.y = this.y / otherVector.y;
  1930. return this;
  1931. };
  1932. /**
  1933. * Divides the current Vector3 coordinates by the passed ones.
  1934. * Returns the updated Vector3.
  1935. */
  1936. Vector2.prototype.divideInPlace = function (otherVector) {
  1937. return this.divideToRef(otherVector, this);
  1938. };
  1939. /**
  1940. * Returns a new Vector2 with current Vector2 negated coordinates.
  1941. */
  1942. Vector2.prototype.negate = function () {
  1943. return new Vector2(-this.x, -this.y);
  1944. };
  1945. /**
  1946. * Multiply the Vector2 coordinates by scale.
  1947. * Returns the updated Vector2.
  1948. */
  1949. Vector2.prototype.scaleInPlace = function (scale) {
  1950. this.x *= scale;
  1951. this.y *= scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1956. */
  1957. Vector2.prototype.scale = function (scale) {
  1958. return new Vector2(this.x * scale, this.y * scale);
  1959. };
  1960. /**
  1961. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1962. */
  1963. Vector2.prototype.equals = function (otherVector) {
  1964. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1965. };
  1966. /**
  1967. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1968. */
  1969. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1970. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1971. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1972. };
  1973. // Properties
  1974. /**
  1975. * Returns the vector length (float).
  1976. */
  1977. Vector2.prototype.length = function () {
  1978. return Math.sqrt(this.x * this.x + this.y * this.y);
  1979. };
  1980. /**
  1981. * Returns the vector squared length (float);
  1982. */
  1983. Vector2.prototype.lengthSquared = function () {
  1984. return (this.x * this.x + this.y * this.y);
  1985. };
  1986. // Methods
  1987. /**
  1988. * Normalize the vector.
  1989. * Returns the updated Vector2.
  1990. */
  1991. Vector2.prototype.normalize = function () {
  1992. var len = this.length();
  1993. if (len === 0)
  1994. return this;
  1995. var num = 1.0 / len;
  1996. this.x *= num;
  1997. this.y *= num;
  1998. return this;
  1999. };
  2000. /**
  2001. * Returns a new Vector2 copied from the Vector2.
  2002. */
  2003. Vector2.prototype.clone = function () {
  2004. return new Vector2(this.x, this.y);
  2005. };
  2006. // Statics
  2007. /**
  2008. * Returns a new Vector2(0, 0)
  2009. */
  2010. Vector2.Zero = function () {
  2011. return new Vector2(0, 0);
  2012. };
  2013. /**
  2014. * Returns a new Vector2(1, 1)
  2015. */
  2016. Vector2.One = function () {
  2017. return new Vector2(1, 1);
  2018. };
  2019. /**
  2020. * Returns a new Vector2 set from the passed index element of the passed array.
  2021. */
  2022. Vector2.FromArray = function (array, offset) {
  2023. if (offset === void 0) { offset = 0; }
  2024. return new Vector2(array[offset], array[offset + 1]);
  2025. };
  2026. /**
  2027. * Sets "result" from the passed index element of the passed array.
  2028. */
  2029. Vector2.FromArrayToRef = function (array, offset, result) {
  2030. result.x = array[offset];
  2031. result.y = array[offset + 1];
  2032. };
  2033. /**
  2034. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2035. */
  2036. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2037. var squared = amount * amount;
  2038. var cubed = amount * squared;
  2039. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2040. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2041. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2042. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2043. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2044. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2045. return new Vector2(x, y);
  2046. };
  2047. /**
  2048. * 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".
  2049. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2050. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2051. */
  2052. Vector2.Clamp = function (value, min, max) {
  2053. var x = value.x;
  2054. x = (x > max.x) ? max.x : x;
  2055. x = (x < min.x) ? min.x : x;
  2056. var y = value.y;
  2057. y = (y > max.y) ? max.y : y;
  2058. y = (y < min.y) ? min.y : y;
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2063. */
  2064. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2065. var squared = amount * amount;
  2066. var cubed = amount * squared;
  2067. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2068. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2069. var part3 = (cubed - (2.0 * squared)) + amount;
  2070. var part4 = cubed - squared;
  2071. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2072. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2077. */
  2078. Vector2.Lerp = function (start, end, amount) {
  2079. var x = start.x + ((end.x - start.x) * amount);
  2080. var y = start.y + ((end.y - start.y) * amount);
  2081. return new Vector2(x, y);
  2082. };
  2083. /**
  2084. * Returns the dot product (float) of the vector "left" and the vector "right".
  2085. */
  2086. Vector2.Dot = function (left, right) {
  2087. return left.x * right.x + left.y * right.y;
  2088. };
  2089. /**
  2090. * Returns a new Vector2 equal to the normalized passed vector.
  2091. */
  2092. Vector2.Normalize = function (vector) {
  2093. var newVector = vector.clone();
  2094. newVector.normalize();
  2095. return newVector;
  2096. };
  2097. /**
  2098. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2099. */
  2100. Vector2.Minimize = function (left, right) {
  2101. var x = (left.x < right.x) ? left.x : right.x;
  2102. var y = (left.y < right.y) ? left.y : right.y;
  2103. return new Vector2(x, y);
  2104. };
  2105. /**
  2106. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2107. */
  2108. Vector2.Maximize = function (left, right) {
  2109. var x = (left.x > right.x) ? left.x : right.x;
  2110. var y = (left.y > right.y) ? left.y : right.y;
  2111. return new Vector2(x, y);
  2112. };
  2113. /**
  2114. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2115. */
  2116. Vector2.Transform = function (vector, transformation) {
  2117. var r = Vector2.Zero();
  2118. Vector2.TransformToRef(vector, transformation, r);
  2119. return r;
  2120. };
  2121. /**
  2122. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2123. */
  2124. Vector2.TransformToRef = function (vector, transformation, result) {
  2125. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2126. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2127. result.x = x;
  2128. result.y = y;
  2129. };
  2130. /**
  2131. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2132. */
  2133. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2134. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2135. var sign = a < 0 ? -1 : 1;
  2136. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2137. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2138. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2139. };
  2140. /**
  2141. * Returns the distance (float) between the vectors "value1" and "value2".
  2142. */
  2143. Vector2.Distance = function (value1, value2) {
  2144. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2145. };
  2146. /**
  2147. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2148. */
  2149. Vector2.DistanceSquared = function (value1, value2) {
  2150. var x = value1.x - value2.x;
  2151. var y = value1.y - value2.y;
  2152. return (x * x) + (y * y);
  2153. };
  2154. /**
  2155. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Center = function (value1, value2) {
  2158. var center = value1.add(value2);
  2159. center.scaleInPlace(0.5);
  2160. return center;
  2161. };
  2162. /**
  2163. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2164. */
  2165. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2166. var l2 = Vector2.DistanceSquared(segA, segB);
  2167. if (l2 === 0.0) {
  2168. return Vector2.Distance(p, segA);
  2169. }
  2170. var v = segB.subtract(segA);
  2171. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2172. var proj = segA.add(v.multiplyByFloats(t, t));
  2173. return Vector2.Distance(p, proj);
  2174. };
  2175. return Vector2;
  2176. }());
  2177. BABYLON.Vector2 = Vector2;
  2178. var Vector3 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2181. * A Vector3 is the main object used in 3D geometry.
  2182. * It can represent etiher the coordinates of a point the space, either a direction.
  2183. */
  2184. function Vector3(x, y, z) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. }
  2189. /**
  2190. * Returns a string with the Vector3 coordinates.
  2191. */
  2192. Vector3.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2194. };
  2195. /**
  2196. * Returns the string "Vector3"
  2197. */
  2198. Vector3.prototype.getClassName = function () {
  2199. return "Vector3";
  2200. };
  2201. /**
  2202. * Returns the Vector hash code.
  2203. */
  2204. Vector3.prototype.getHashCode = function () {
  2205. var hash = this.x || 0;
  2206. hash = (hash * 397) ^ (this.y || 0);
  2207. hash = (hash * 397) ^ (this.z || 0);
  2208. return hash;
  2209. };
  2210. // Operators
  2211. /**
  2212. * Returns a new array with three elements : the coordinates the Vector3.
  2213. */
  2214. Vector3.prototype.asArray = function () {
  2215. var result = [];
  2216. this.toArray(result, 0);
  2217. return result;
  2218. };
  2219. /**
  2220. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2221. * Returns the Vector3.
  2222. */
  2223. Vector3.prototype.toArray = function (array, index) {
  2224. if (index === void 0) { index = 0; }
  2225. array[index] = this.x;
  2226. array[index + 1] = this.y;
  2227. array[index + 2] = this.z;
  2228. return this;
  2229. };
  2230. /**
  2231. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2232. */
  2233. Vector3.prototype.toQuaternion = function () {
  2234. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2235. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2236. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2237. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2238. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2239. var cosy = Math.cos(this.y * 0.5);
  2240. var siny = Math.sin(this.y * 0.5);
  2241. result.x = coszMinusx * siny;
  2242. result.y = -sinzMinusx * siny;
  2243. result.z = sinxPlusz * cosy;
  2244. result.w = cosxPlusz * cosy;
  2245. return result;
  2246. };
  2247. /**
  2248. * Adds the passed vector to the current Vector3.
  2249. * Returns the updated Vector3.
  2250. */
  2251. Vector3.prototype.addInPlace = function (otherVector) {
  2252. this.x += otherVector.x;
  2253. this.y += otherVector.y;
  2254. this.z += otherVector.z;
  2255. return this;
  2256. };
  2257. /**
  2258. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2259. */
  2260. Vector3.prototype.add = function (otherVector) {
  2261. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2262. };
  2263. /**
  2264. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2265. * Returns the current Vector3.
  2266. */
  2267. Vector3.prototype.addToRef = function (otherVector, result) {
  2268. result.x = this.x + otherVector.x;
  2269. result.y = this.y + otherVector.y;
  2270. result.z = this.z + otherVector.z;
  2271. return this;
  2272. };
  2273. /**
  2274. * Subtract the passed vector from the current Vector3.
  2275. * Returns the updated Vector3.
  2276. */
  2277. Vector3.prototype.subtractInPlace = function (otherVector) {
  2278. this.x -= otherVector.x;
  2279. this.y -= otherVector.y;
  2280. this.z -= otherVector.z;
  2281. return this;
  2282. };
  2283. /**
  2284. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2285. */
  2286. Vector3.prototype.subtract = function (otherVector) {
  2287. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2288. };
  2289. /**
  2290. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2291. * Returns the current Vector3.
  2292. */
  2293. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2294. result.x = this.x - otherVector.x;
  2295. result.y = this.y - otherVector.y;
  2296. result.z = this.z - otherVector.z;
  2297. return this;
  2298. };
  2299. /**
  2300. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2301. */
  2302. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2303. return new Vector3(this.x - x, this.y - y, this.z - z);
  2304. };
  2305. /**
  2306. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2307. * Returns the current Vector3.
  2308. */
  2309. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2310. result.x = this.x - x;
  2311. result.y = this.y - y;
  2312. result.z = this.z - z;
  2313. return this;
  2314. };
  2315. /**
  2316. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2317. */
  2318. Vector3.prototype.negate = function () {
  2319. return new Vector3(-this.x, -this.y, -this.z);
  2320. };
  2321. /**
  2322. * Multiplies the Vector3 coordinates by the float "scale".
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.scaleInPlace = function (scale) {
  2326. this.x *= scale;
  2327. this.y *= scale;
  2328. this.z *= scale;
  2329. return this;
  2330. };
  2331. /**
  2332. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2333. */
  2334. Vector3.prototype.scale = function (scale) {
  2335. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2336. };
  2337. /**
  2338. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2339. * Returns the current Vector3.
  2340. */
  2341. Vector3.prototype.scaleToRef = function (scale, result) {
  2342. result.x = this.x * scale;
  2343. result.y = this.y * scale;
  2344. result.z = this.z * scale;
  2345. return this;
  2346. };
  2347. /**
  2348. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2349. */
  2350. Vector3.prototype.equals = function (otherVector) {
  2351. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2352. };
  2353. /**
  2354. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2355. */
  2356. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2357. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2358. 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);
  2359. };
  2360. /**
  2361. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2362. */
  2363. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2364. return this.x === x && this.y === y && this.z === z;
  2365. };
  2366. /**
  2367. * Muliplies the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2371. this.x *= otherVector.x;
  2372. this.y *= otherVector.y;
  2373. this.z *= otherVector.z;
  2374. return this;
  2375. };
  2376. /**
  2377. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2378. */
  2379. Vector3.prototype.multiply = function (otherVector) {
  2380. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2381. };
  2382. /**
  2383. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2384. * Returns the current Vector3.
  2385. */
  2386. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. result.z = this.z * otherVector.z;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2394. */
  2395. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2396. return new Vector3(this.x * x, this.y * y, this.z * z);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2400. */
  2401. Vector3.prototype.divide = function (otherVector) {
  2402. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2403. };
  2404. /**
  2405. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2406. * Returns the current Vector3.
  2407. */
  2408. Vector3.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. result.z = this.z / otherVector.z;
  2412. return this;
  2413. };
  2414. /**
  2415. * Divides the current Vector3 coordinates by the passed ones.
  2416. * Returns the updated Vector3.
  2417. */
  2418. Vector3.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2423. * Returns the updated Vector3.
  2424. */
  2425. Vector3.prototype.MinimizeInPlace = function (other) {
  2426. if (other.x < this.x)
  2427. this.x = other.x;
  2428. if (other.y < this.y)
  2429. this.y = other.y;
  2430. if (other.z < this.z)
  2431. this.z = other.z;
  2432. return this;
  2433. };
  2434. /**
  2435. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2436. * Returns the updated Vector3.
  2437. */
  2438. Vector3.prototype.MaximizeInPlace = function (other) {
  2439. if (other.x > this.x)
  2440. this.x = other.x;
  2441. if (other.y > this.y)
  2442. this.y = other.y;
  2443. if (other.z > this.z)
  2444. this.z = other.z;
  2445. return this;
  2446. };
  2447. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2448. /**
  2449. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2450. */
  2451. get: function () {
  2452. var absX = Math.abs(this.x);
  2453. var absY = Math.abs(this.y);
  2454. if (absX !== absY) {
  2455. return true;
  2456. }
  2457. var absZ = Math.abs(this.z);
  2458. if (absX !== absZ) {
  2459. return true;
  2460. }
  2461. if (absY !== absZ) {
  2462. return true;
  2463. }
  2464. return false;
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. // Properties
  2470. /**
  2471. * Returns the length of the Vector3 (float).
  2472. */
  2473. Vector3.prototype.length = function () {
  2474. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2475. };
  2476. /**
  2477. * Returns the squared length of the Vector3 (float).
  2478. */
  2479. Vector3.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2481. };
  2482. /**
  2483. * Normalize the current Vector3.
  2484. * Returns the updated Vector3.
  2485. * /!\ In place operation.
  2486. */
  2487. Vector3.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0 || len === 1.0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. this.z *= num;
  2495. return this;
  2496. };
  2497. /**
  2498. * Normalize the current Vector3 to a new vector.
  2499. * @returns the new Vector3.
  2500. */
  2501. Vector3.prototype.normalizeToNew = function () {
  2502. var normalized = new Vector3(0, 0, 0);
  2503. this.normalizeToRef(normalized);
  2504. return normalized;
  2505. };
  2506. /**
  2507. * Normalize the current Vector3 to the reference.
  2508. * @param the reference to update.
  2509. * @returns the updated Vector3.
  2510. */
  2511. Vector3.prototype.normalizeToRef = function (reference) {
  2512. var len = this.length();
  2513. if (len === 0 || len === 1.0) {
  2514. reference.set(this.x, this.y, this.z);
  2515. return reference;
  2516. }
  2517. var scale = 1.0 / len;
  2518. this.scaleToRef(scale, reference);
  2519. return reference;
  2520. };
  2521. /**
  2522. * Returns a new Vector3 copied from the current Vector3.
  2523. */
  2524. Vector3.prototype.clone = function () {
  2525. return new Vector3(this.x, this.y, this.z);
  2526. };
  2527. /**
  2528. * Copies the passed vector coordinates to the current Vector3 ones.
  2529. * Returns the updated Vector3.
  2530. */
  2531. Vector3.prototype.copyFrom = function (source) {
  2532. this.x = source.x;
  2533. this.y = source.y;
  2534. this.z = source.z;
  2535. return this;
  2536. };
  2537. /**
  2538. * Copies the passed floats to the current Vector3 coordinates.
  2539. * Returns the updated Vector3.
  2540. */
  2541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2542. this.x = x;
  2543. this.y = y;
  2544. this.z = z;
  2545. return this;
  2546. };
  2547. /**
  2548. * Copies the passed floats to the current Vector3 coordinates.
  2549. * Returns the updated Vector3.
  2550. */
  2551. Vector3.prototype.set = function (x, y, z) {
  2552. return this.copyFromFloats(x, y, z);
  2553. };
  2554. // Statics
  2555. /**
  2556. *
  2557. */
  2558. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2559. var d0 = Vector3.Dot(vector0, axis) - size;
  2560. var d1 = Vector3.Dot(vector1, axis) - size;
  2561. var s = d0 / (d0 - d1);
  2562. return s;
  2563. };
  2564. /**
  2565. * Get angle between two vectors.
  2566. * @param vector0 angle between vector0 and vector1
  2567. * @param vector1 angle between vector0 and vector1
  2568. * @param normal direction of the normal.
  2569. * @return the angle between vector0 and vector1.
  2570. */
  2571. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2572. var v0 = vector0.clone().normalize();
  2573. var v1 = vector1.clone().normalize();
  2574. var dot = Vector3.Dot(v0, v1);
  2575. var n = Vector3.Cross(v0, v1);
  2576. if (Vector3.Dot(n, normal) > 0) {
  2577. return Math.acos(dot);
  2578. }
  2579. return -Math.acos(dot);
  2580. };
  2581. /**
  2582. * Returns a new Vector3 set from the index "offset" of the passed array.
  2583. */
  2584. Vector3.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2589. };
  2590. /**
  2591. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2592. * This function is deprecated. Use FromArray instead.
  2593. */
  2594. Vector3.FromFloatArray = function (array, offset) {
  2595. return Vector3.FromArray(array, offset);
  2596. };
  2597. /**
  2598. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2599. */
  2600. Vector3.FromArrayToRef = function (array, offset, result) {
  2601. result.x = array[offset];
  2602. result.y = array[offset + 1];
  2603. result.z = array[offset + 2];
  2604. };
  2605. /**
  2606. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2607. * This function is deprecated. Use FromArrayToRef instead.
  2608. */
  2609. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2610. return Vector3.FromArrayToRef(array, offset, result);
  2611. };
  2612. /**
  2613. * Sets the passed vector "result" with the passed floats.
  2614. */
  2615. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2616. result.x = x;
  2617. result.y = y;
  2618. result.z = z;
  2619. };
  2620. /**
  2621. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2622. */
  2623. Vector3.Zero = function () {
  2624. return new Vector3(0.0, 0.0, 0.0);
  2625. };
  2626. /**
  2627. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2628. */
  2629. Vector3.One = function () {
  2630. return new Vector3(1.0, 1.0, 1.0);
  2631. };
  2632. /**
  2633. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2634. */
  2635. Vector3.Up = function () {
  2636. return new Vector3(0.0, 1.0, 0.0);
  2637. };
  2638. /**
  2639. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2640. */
  2641. Vector3.Forward = function () {
  2642. return new Vector3(0.0, 0.0, 1.0);
  2643. };
  2644. /**
  2645. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2646. */
  2647. Vector3.Right = function () {
  2648. return new Vector3(1.0, 0.0, 0.0);
  2649. };
  2650. /**
  2651. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2652. */
  2653. Vector3.Left = function () {
  2654. return new Vector3(-1.0, 0.0, 0.0);
  2655. };
  2656. /**
  2657. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2658. * This method computes tranformed coordinates only, not transformed direction vectors.
  2659. */
  2660. Vector3.TransformCoordinates = function (vector, transformation) {
  2661. var result = Vector3.Zero();
  2662. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2663. return result;
  2664. };
  2665. /**
  2666. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2667. * This method computes tranformed coordinates only, not transformed direction vectors.
  2668. */
  2669. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2670. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2671. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2672. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2673. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2674. result.x = x / w;
  2675. result.y = y / w;
  2676. result.z = z / w;
  2677. };
  2678. /**
  2679. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2680. * This method computes tranformed coordinates only, not transformed direction vectors.
  2681. */
  2682. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2683. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2684. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2685. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2686. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2687. result.x = rx / rw;
  2688. result.y = ry / rw;
  2689. result.z = rz / rw;
  2690. };
  2691. /**
  2692. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2693. * This methods computes transformed normalized direction vectors only.
  2694. */
  2695. Vector3.TransformNormal = function (vector, transformation) {
  2696. var result = Vector3.Zero();
  2697. Vector3.TransformNormalToRef(vector, transformation, result);
  2698. return result;
  2699. };
  2700. /**
  2701. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2702. * This methods computes transformed normalized direction vectors only.
  2703. */
  2704. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2705. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2706. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2707. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2708. result.x = x;
  2709. result.y = y;
  2710. result.z = z;
  2711. };
  2712. /**
  2713. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2714. * This methods computes transformed normalized direction vectors only.
  2715. */
  2716. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2717. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2718. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2719. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2720. };
  2721. /**
  2722. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2723. */
  2724. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2725. var squared = amount * amount;
  2726. var cubed = amount * squared;
  2727. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2728. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2729. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2730. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2731. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2732. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2733. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2734. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2735. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2736. return new Vector3(x, y, z);
  2737. };
  2738. /**
  2739. * 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".
  2740. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2741. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2742. */
  2743. Vector3.Clamp = function (value, min, max) {
  2744. var x = value.x;
  2745. x = (x > max.x) ? max.x : x;
  2746. x = (x < min.x) ? min.x : x;
  2747. var y = value.y;
  2748. y = (y > max.y) ? max.y : y;
  2749. y = (y < min.y) ? min.y : y;
  2750. var z = value.z;
  2751. z = (z > max.z) ? max.z : z;
  2752. z = (z < min.z) ? min.z : z;
  2753. return new Vector3(x, y, z);
  2754. };
  2755. /**
  2756. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2757. */
  2758. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2759. var squared = amount * amount;
  2760. var cubed = amount * squared;
  2761. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2762. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2763. var part3 = (cubed - (2.0 * squared)) + amount;
  2764. var part4 = cubed - squared;
  2765. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2766. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2767. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2768. return new Vector3(x, y, z);
  2769. };
  2770. /**
  2771. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2772. */
  2773. Vector3.Lerp = function (start, end, amount) {
  2774. var result = new Vector3(0, 0, 0);
  2775. Vector3.LerpToRef(start, end, amount, result);
  2776. return result;
  2777. };
  2778. /**
  2779. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2780. */
  2781. Vector3.LerpToRef = function (start, end, amount, result) {
  2782. result.x = start.x + ((end.x - start.x) * amount);
  2783. result.y = start.y + ((end.y - start.y) * amount);
  2784. result.z = start.z + ((end.z - start.z) * amount);
  2785. };
  2786. /**
  2787. * Returns the dot product (float) between the vectors "left" and "right".
  2788. */
  2789. Vector3.Dot = function (left, right) {
  2790. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2791. };
  2792. /**
  2793. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2794. * The cross product is then orthogonal to both "left" and "right".
  2795. */
  2796. Vector3.Cross = function (left, right) {
  2797. var result = Vector3.Zero();
  2798. Vector3.CrossToRef(left, right, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed vector "result" with the cross product of "left" and "right".
  2803. * The cross product is then orthogonal to both "left" and "right".
  2804. */
  2805. Vector3.CrossToRef = function (left, right, result) {
  2806. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2807. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2808. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2809. result.copyFrom(MathTmp.Vector3[0]);
  2810. };
  2811. /**
  2812. * Returns a new Vector3 as the normalization of the passed vector.
  2813. */
  2814. Vector3.Normalize = function (vector) {
  2815. var result = Vector3.Zero();
  2816. Vector3.NormalizeToRef(vector, result);
  2817. return result;
  2818. };
  2819. /**
  2820. * Sets the passed vector "result" with the normalization of the passed first vector.
  2821. */
  2822. Vector3.NormalizeToRef = function (vector, result) {
  2823. result.copyFrom(vector);
  2824. result.normalize();
  2825. };
  2826. Vector3.Project = function (vector, world, transform, viewport) {
  2827. var cw = viewport.width;
  2828. var ch = viewport.height;
  2829. var cx = viewport.x;
  2830. var cy = viewport.y;
  2831. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2832. 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);
  2833. var matrix = MathTmp.Matrix[0];
  2834. world.multiplyToRef(transform, matrix);
  2835. matrix.multiplyToRef(viewportMatrix, matrix);
  2836. return Vector3.TransformCoordinates(vector, matrix);
  2837. };
  2838. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2839. var matrix = MathTmp.Matrix[0];
  2840. world.multiplyToRef(transform, matrix);
  2841. matrix.invert();
  2842. source.x = source.x / viewportWidth * 2 - 1;
  2843. source.y = -(source.y / viewportHeight * 2 - 1);
  2844. var vector = Vector3.TransformCoordinates(source, matrix);
  2845. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2846. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2847. vector = vector.scale(1.0 / num);
  2848. }
  2849. return vector;
  2850. };
  2851. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2852. var result = Vector3.Zero();
  2853. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2854. return result;
  2855. };
  2856. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2857. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2858. };
  2859. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2860. var matrix = MathTmp.Matrix[0];
  2861. world.multiplyToRef(view, matrix);
  2862. matrix.multiplyToRef(projection, matrix);
  2863. matrix.invert();
  2864. var screenSource = MathTmp.Vector3[0];
  2865. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2866. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2867. screenSource.z = 2 * sourceZ - 1.0;
  2868. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2869. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2870. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2871. result.scaleInPlace(1.0 / num);
  2872. }
  2873. };
  2874. Vector3.Minimize = function (left, right) {
  2875. var min = left.clone();
  2876. min.MinimizeInPlace(right);
  2877. return min;
  2878. };
  2879. Vector3.Maximize = function (left, right) {
  2880. var max = left.clone();
  2881. max.MaximizeInPlace(right);
  2882. return max;
  2883. };
  2884. /**
  2885. * Returns the distance (float) between the vectors "value1" and "value2".
  2886. */
  2887. Vector3.Distance = function (value1, value2) {
  2888. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2889. };
  2890. /**
  2891. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2892. */
  2893. Vector3.DistanceSquared = function (value1, value2) {
  2894. var x = value1.x - value2.x;
  2895. var y = value1.y - value2.y;
  2896. var z = value1.z - value2.z;
  2897. return (x * x) + (y * y) + (z * z);
  2898. };
  2899. /**
  2900. * Returns a new Vector3 located at the center between "value1" and "value2".
  2901. */
  2902. Vector3.Center = function (value1, value2) {
  2903. var center = value1.add(value2);
  2904. center.scaleInPlace(0.5);
  2905. return center;
  2906. };
  2907. /**
  2908. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2909. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2910. * to something in order to rotate it from its local system to the given target system.
  2911. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2912. * Returns a new Vector3.
  2913. */
  2914. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2915. var rotation = Vector3.Zero();
  2916. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2917. return rotation;
  2918. };
  2919. /**
  2920. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2921. */
  2922. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2923. var quat = MathTmp.Quaternion[0];
  2924. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2925. quat.toEulerAnglesToRef(ref);
  2926. };
  2927. return Vector3;
  2928. }());
  2929. BABYLON.Vector3 = Vector3;
  2930. //Vector4 class created for EulerAngle class conversion to Quaternion
  2931. var Vector4 = /** @class */ (function () {
  2932. /**
  2933. * Creates a Vector4 object from the passed floats.
  2934. */
  2935. function Vector4(x, y, z, w) {
  2936. this.x = x;
  2937. this.y = y;
  2938. this.z = z;
  2939. this.w = w;
  2940. }
  2941. /**
  2942. * Returns the string with the Vector4 coordinates.
  2943. */
  2944. Vector4.prototype.toString = function () {
  2945. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2946. };
  2947. /**
  2948. * Returns the string "Vector4".
  2949. */
  2950. Vector4.prototype.getClassName = function () {
  2951. return "Vector4";
  2952. };
  2953. /**
  2954. * Returns the Vector4 hash code.
  2955. */
  2956. Vector4.prototype.getHashCode = function () {
  2957. var hash = this.x || 0;
  2958. hash = (hash * 397) ^ (this.y || 0);
  2959. hash = (hash * 397) ^ (this.z || 0);
  2960. hash = (hash * 397) ^ (this.w || 0);
  2961. return hash;
  2962. };
  2963. // Operators
  2964. /**
  2965. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2966. */
  2967. Vector4.prototype.asArray = function () {
  2968. var result = new Array();
  2969. this.toArray(result, 0);
  2970. return result;
  2971. };
  2972. /**
  2973. * Populates the passed array from the passed index with the Vector4 coordinates.
  2974. * Returns the Vector4.
  2975. */
  2976. Vector4.prototype.toArray = function (array, index) {
  2977. if (index === undefined) {
  2978. index = 0;
  2979. }
  2980. array[index] = this.x;
  2981. array[index + 1] = this.y;
  2982. array[index + 2] = this.z;
  2983. array[index + 3] = this.w;
  2984. return this;
  2985. };
  2986. /**
  2987. * Adds the passed vector to the current Vector4.
  2988. * Returns the updated Vector4.
  2989. */
  2990. Vector4.prototype.addInPlace = function (otherVector) {
  2991. this.x += otherVector.x;
  2992. this.y += otherVector.y;
  2993. this.z += otherVector.z;
  2994. this.w += otherVector.w;
  2995. return this;
  2996. };
  2997. /**
  2998. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2999. */
  3000. Vector4.prototype.add = function (otherVector) {
  3001. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3002. };
  3003. /**
  3004. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3005. * Returns the current Vector4.
  3006. */
  3007. Vector4.prototype.addToRef = function (otherVector, result) {
  3008. result.x = this.x + otherVector.x;
  3009. result.y = this.y + otherVector.y;
  3010. result.z = this.z + otherVector.z;
  3011. result.w = this.w + otherVector.w;
  3012. return this;
  3013. };
  3014. /**
  3015. * Subtract in place the passed vector from the current Vector4.
  3016. * Returns the updated Vector4.
  3017. */
  3018. Vector4.prototype.subtractInPlace = function (otherVector) {
  3019. this.x -= otherVector.x;
  3020. this.y -= otherVector.y;
  3021. this.z -= otherVector.z;
  3022. this.w -= otherVector.w;
  3023. return this;
  3024. };
  3025. /**
  3026. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3027. */
  3028. Vector4.prototype.subtract = function (otherVector) {
  3029. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3030. };
  3031. /**
  3032. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3033. * Returns the current Vector4.
  3034. */
  3035. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3036. result.x = this.x - otherVector.x;
  3037. result.y = this.y - otherVector.y;
  3038. result.z = this.z - otherVector.z;
  3039. result.w = this.w - otherVector.w;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3044. */
  3045. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3046. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3047. };
  3048. /**
  3049. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3050. * Returns the current Vector4.
  3051. */
  3052. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3053. result.x = this.x - x;
  3054. result.y = this.y - y;
  3055. result.z = this.z - z;
  3056. result.w = this.w - w;
  3057. return this;
  3058. };
  3059. /**
  3060. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3061. */
  3062. Vector4.prototype.negate = function () {
  3063. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3064. };
  3065. /**
  3066. * Multiplies the current Vector4 coordinates by scale (float).
  3067. * Returns the updated Vector4.
  3068. */
  3069. Vector4.prototype.scaleInPlace = function (scale) {
  3070. this.x *= scale;
  3071. this.y *= scale;
  3072. this.z *= scale;
  3073. this.w *= scale;
  3074. return this;
  3075. };
  3076. /**
  3077. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3078. */
  3079. Vector4.prototype.scale = function (scale) {
  3080. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3081. };
  3082. /**
  3083. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3084. * Returns the current Vector4.
  3085. */
  3086. Vector4.prototype.scaleToRef = function (scale, result) {
  3087. result.x = this.x * scale;
  3088. result.y = this.y * scale;
  3089. result.z = this.z * scale;
  3090. result.w = this.w * scale;
  3091. return this;
  3092. };
  3093. /**
  3094. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3095. */
  3096. Vector4.prototype.equals = function (otherVector) {
  3097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3098. };
  3099. /**
  3100. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3101. */
  3102. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3103. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3104. return otherVector
  3105. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3106. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3107. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3108. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3109. };
  3110. /**
  3111. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3112. */
  3113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3114. return this.x === x && this.y === y && this.z === z && this.w === w;
  3115. };
  3116. /**
  3117. * Multiplies in place the current Vector4 by the passed one.
  3118. * Returns the updated Vector4.
  3119. */
  3120. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3121. this.x *= otherVector.x;
  3122. this.y *= otherVector.y;
  3123. this.z *= otherVector.z;
  3124. this.w *= otherVector.w;
  3125. return this;
  3126. };
  3127. /**
  3128. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3129. */
  3130. Vector4.prototype.multiply = function (otherVector) {
  3131. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3132. };
  3133. /**
  3134. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3135. * Returns the current Vector4.
  3136. */
  3137. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3138. result.x = this.x * otherVector.x;
  3139. result.y = this.y * otherVector.y;
  3140. result.z = this.z * otherVector.z;
  3141. result.w = this.w * otherVector.w;
  3142. return this;
  3143. };
  3144. /**
  3145. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3146. */
  3147. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3148. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3149. };
  3150. /**
  3151. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3152. */
  3153. Vector4.prototype.divide = function (otherVector) {
  3154. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3155. };
  3156. /**
  3157. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3158. * Returns the current Vector4.
  3159. */
  3160. Vector4.prototype.divideToRef = function (otherVector, result) {
  3161. result.x = this.x / otherVector.x;
  3162. result.y = this.y / otherVector.y;
  3163. result.z = this.z / otherVector.z;
  3164. result.w = this.w / otherVector.w;
  3165. return this;
  3166. };
  3167. /**
  3168. * Divides the current Vector3 coordinates by the passed ones.
  3169. * Returns the updated Vector3.
  3170. */
  3171. Vector4.prototype.divideInPlace = function (otherVector) {
  3172. return this.divideToRef(otherVector, this);
  3173. };
  3174. /**
  3175. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3176. */
  3177. Vector4.prototype.MinimizeInPlace = function (other) {
  3178. if (other.x < this.x)
  3179. this.x = other.x;
  3180. if (other.y < this.y)
  3181. this.y = other.y;
  3182. if (other.z < this.z)
  3183. this.z = other.z;
  3184. if (other.w < this.w)
  3185. this.w = other.w;
  3186. return this;
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MaximizeInPlace = function (other) {
  3192. if (other.x > this.x)
  3193. this.x = other.x;
  3194. if (other.y > this.y)
  3195. this.y = other.y;
  3196. if (other.z > this.z)
  3197. this.z = other.z;
  3198. if (other.w > this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. // Properties
  3203. /**
  3204. * Returns the Vector4 length (float).
  3205. */
  3206. Vector4.prototype.length = function () {
  3207. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3208. };
  3209. /**
  3210. * Returns the Vector4 squared length (float).
  3211. */
  3212. Vector4.prototype.lengthSquared = function () {
  3213. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3214. };
  3215. // Methods
  3216. /**
  3217. * Normalizes in place the Vector4.
  3218. * Returns the updated Vector4.
  3219. */
  3220. Vector4.prototype.normalize = function () {
  3221. var len = this.length();
  3222. if (len === 0)
  3223. return this;
  3224. var num = 1.0 / len;
  3225. this.x *= num;
  3226. this.y *= num;
  3227. this.z *= num;
  3228. this.w *= num;
  3229. return this;
  3230. };
  3231. /**
  3232. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3233. */
  3234. Vector4.prototype.toVector3 = function () {
  3235. return new Vector3(this.x, this.y, this.z);
  3236. };
  3237. /**
  3238. * Returns a new Vector4 copied from the current one.
  3239. */
  3240. Vector4.prototype.clone = function () {
  3241. return new Vector4(this.x, this.y, this.z, this.w);
  3242. };
  3243. /**
  3244. * Updates the current Vector4 with the passed one coordinates.
  3245. * Returns the updated Vector4.
  3246. */
  3247. Vector4.prototype.copyFrom = function (source) {
  3248. this.x = source.x;
  3249. this.y = source.y;
  3250. this.z = source.z;
  3251. this.w = source.w;
  3252. return this;
  3253. };
  3254. /**
  3255. * Updates the current Vector4 coordinates with the passed floats.
  3256. * Returns the updated Vector4.
  3257. */
  3258. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3259. this.x = x;
  3260. this.y = y;
  3261. this.z = z;
  3262. this.w = w;
  3263. return this;
  3264. };
  3265. /**
  3266. * Updates the current Vector4 coordinates with the passed floats.
  3267. * Returns the updated Vector4.
  3268. */
  3269. Vector4.prototype.set = function (x, y, z, w) {
  3270. return this.copyFromFloats(x, y, z, w);
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Vector4 set from the starting index of the passed array.
  3275. */
  3276. Vector4.FromArray = function (array, offset) {
  3277. if (!offset) {
  3278. offset = 0;
  3279. }
  3280. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3281. };
  3282. /**
  3283. * Updates the passed vector "result" from the starting index of the passed array.
  3284. */
  3285. Vector4.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. result.w = array[offset + 3];
  3290. };
  3291. /**
  3292. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3293. */
  3294. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3295. Vector4.FromArrayToRef(array, offset, result);
  3296. };
  3297. /**
  3298. * Updates the passed vector "result" coordinates from the passed floats.
  3299. */
  3300. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. result.w = w;
  3305. };
  3306. /**
  3307. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3308. */
  3309. Vector4.Zero = function () {
  3310. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3314. */
  3315. Vector4.One = function () {
  3316. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3317. };
  3318. /**
  3319. * Returns a new normalized Vector4 from the passed one.
  3320. */
  3321. Vector4.Normalize = function (vector) {
  3322. var result = Vector4.Zero();
  3323. Vector4.NormalizeToRef(vector, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Updates the passed vector "result" from the normalization of the passed one.
  3328. */
  3329. Vector4.NormalizeToRef = function (vector, result) {
  3330. result.copyFrom(vector);
  3331. result.normalize();
  3332. };
  3333. Vector4.Minimize = function (left, right) {
  3334. var min = left.clone();
  3335. min.MinimizeInPlace(right);
  3336. return min;
  3337. };
  3338. Vector4.Maximize = function (left, right) {
  3339. var max = left.clone();
  3340. max.MaximizeInPlace(right);
  3341. return max;
  3342. };
  3343. /**
  3344. * Returns the distance (float) between the vectors "value1" and "value2".
  3345. */
  3346. Vector4.Distance = function (value1, value2) {
  3347. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3348. };
  3349. /**
  3350. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3351. */
  3352. Vector4.DistanceSquared = function (value1, value2) {
  3353. var x = value1.x - value2.x;
  3354. var y = value1.y - value2.y;
  3355. var z = value1.z - value2.z;
  3356. var w = value1.w - value2.w;
  3357. return (x * x) + (y * y) + (z * z) + (w * w);
  3358. };
  3359. /**
  3360. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3361. */
  3362. Vector4.Center = function (value1, value2) {
  3363. var center = value1.add(value2);
  3364. center.scaleInPlace(0.5);
  3365. return center;
  3366. };
  3367. /**
  3368. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3369. * This methods computes transformed normalized direction vectors only.
  3370. */
  3371. Vector4.TransformNormal = function (vector, transformation) {
  3372. var result = Vector4.Zero();
  3373. Vector4.TransformNormalToRef(vector, transformation, result);
  3374. return result;
  3375. };
  3376. /**
  3377. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3378. * This methods computes transformed normalized direction vectors only.
  3379. */
  3380. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3381. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3382. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3383. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3384. result.x = x;
  3385. result.y = y;
  3386. result.z = z;
  3387. result.w = vector.w;
  3388. };
  3389. /**
  3390. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3391. * This methods computes transformed normalized direction vectors only.
  3392. */
  3393. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3394. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3395. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3396. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3397. result.w = w;
  3398. };
  3399. return Vector4;
  3400. }());
  3401. BABYLON.Vector4 = Vector4;
  3402. var Size = /** @class */ (function () {
  3403. /**
  3404. * Creates a Size object from the passed width and height (floats).
  3405. */
  3406. function Size(width, height) {
  3407. this.width = width;
  3408. this.height = height;
  3409. }
  3410. // Returns a string with the Size width and height.
  3411. Size.prototype.toString = function () {
  3412. return "{W: " + this.width + ", H: " + this.height + "}";
  3413. };
  3414. /**
  3415. * Returns the string "Size"
  3416. */
  3417. Size.prototype.getClassName = function () {
  3418. return "Size";
  3419. };
  3420. /**
  3421. * Returns the Size hash code.
  3422. */
  3423. Size.prototype.getHashCode = function () {
  3424. var hash = this.width || 0;
  3425. hash = (hash * 397) ^ (this.height || 0);
  3426. return hash;
  3427. };
  3428. /**
  3429. * Updates the current size from the passed one.
  3430. * Returns the updated Size.
  3431. */
  3432. Size.prototype.copyFrom = function (src) {
  3433. this.width = src.width;
  3434. this.height = src.height;
  3435. };
  3436. /**
  3437. * Updates in place the current Size from the passed floats.
  3438. * Returns the updated Size.
  3439. */
  3440. Size.prototype.copyFromFloats = function (width, height) {
  3441. this.width = width;
  3442. this.height = height;
  3443. return this;
  3444. };
  3445. /**
  3446. * Updates in place the current Size from the passed floats.
  3447. * Returns the updated Size.
  3448. */
  3449. Size.prototype.set = function (width, height) {
  3450. return this.copyFromFloats(width, height);
  3451. };
  3452. /**
  3453. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3454. */
  3455. Size.prototype.multiplyByFloats = function (w, h) {
  3456. return new Size(this.width * w, this.height * h);
  3457. };
  3458. /**
  3459. * Returns a new Size copied from the passed one.
  3460. */
  3461. Size.prototype.clone = function () {
  3462. return new Size(this.width, this.height);
  3463. };
  3464. /**
  3465. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3466. */
  3467. Size.prototype.equals = function (other) {
  3468. if (!other) {
  3469. return false;
  3470. }
  3471. return (this.width === other.width) && (this.height === other.height);
  3472. };
  3473. Object.defineProperty(Size.prototype, "surface", {
  3474. /**
  3475. * Returns the surface of the Size : width * height (float).
  3476. */
  3477. get: function () {
  3478. return this.width * this.height;
  3479. },
  3480. enumerable: true,
  3481. configurable: true
  3482. });
  3483. /**
  3484. * Returns a new Size set to (0.0, 0.0)
  3485. */
  3486. Size.Zero = function () {
  3487. return new Size(0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Size set as the addition result of the current Size and the passed one.
  3491. */
  3492. Size.prototype.add = function (otherSize) {
  3493. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3494. return r;
  3495. };
  3496. /**
  3497. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3498. */
  3499. Size.prototype.subtract = function (otherSize) {
  3500. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3501. return r;
  3502. };
  3503. /**
  3504. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3505. */
  3506. Size.Lerp = function (start, end, amount) {
  3507. var w = start.width + ((end.width - start.width) * amount);
  3508. var h = start.height + ((end.height - start.height) * amount);
  3509. return new Size(w, h);
  3510. };
  3511. return Size;
  3512. }());
  3513. BABYLON.Size = Size;
  3514. var Quaternion = /** @class */ (function () {
  3515. /**
  3516. * Creates a new Quaternion from the passed floats.
  3517. */
  3518. function Quaternion(x, y, z, w) {
  3519. if (x === void 0) { x = 0.0; }
  3520. if (y === void 0) { y = 0.0; }
  3521. if (z === void 0) { z = 0.0; }
  3522. if (w === void 0) { w = 1.0; }
  3523. this.x = x;
  3524. this.y = y;
  3525. this.z = z;
  3526. this.w = w;
  3527. }
  3528. /**
  3529. * Returns a string with the Quaternion coordinates.
  3530. */
  3531. Quaternion.prototype.toString = function () {
  3532. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3533. };
  3534. /**
  3535. * Returns the string "Quaternion".
  3536. */
  3537. Quaternion.prototype.getClassName = function () {
  3538. return "Quaternion";
  3539. };
  3540. /**
  3541. * Returns the Quaternion hash code.
  3542. */
  3543. Quaternion.prototype.getHashCode = function () {
  3544. var hash = this.x || 0;
  3545. hash = (hash * 397) ^ (this.y || 0);
  3546. hash = (hash * 397) ^ (this.z || 0);
  3547. hash = (hash * 397) ^ (this.w || 0);
  3548. return hash;
  3549. };
  3550. /**
  3551. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3552. */
  3553. Quaternion.prototype.asArray = function () {
  3554. return [this.x, this.y, this.z, this.w];
  3555. };
  3556. /**
  3557. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3558. */
  3559. Quaternion.prototype.equals = function (otherQuaternion) {
  3560. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3561. };
  3562. /**
  3563. * Returns a new Quaternion copied from the current one.
  3564. */
  3565. Quaternion.prototype.clone = function () {
  3566. return new Quaternion(this.x, this.y, this.z, this.w);
  3567. };
  3568. /**
  3569. * Updates the current Quaternion from the passed one coordinates.
  3570. * Returns the updated Quaterion.
  3571. */
  3572. Quaternion.prototype.copyFrom = function (other) {
  3573. this.x = other.x;
  3574. this.y = other.y;
  3575. this.z = other.z;
  3576. this.w = other.w;
  3577. return this;
  3578. };
  3579. /**
  3580. * Updates the current Quaternion from the passed float coordinates.
  3581. * Returns the updated Quaterion.
  3582. */
  3583. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3584. this.x = x;
  3585. this.y = y;
  3586. this.z = z;
  3587. this.w = w;
  3588. return this;
  3589. };
  3590. /**
  3591. * Updates the current Quaternion from the passed float coordinates.
  3592. * Returns the updated Quaterion.
  3593. */
  3594. Quaternion.prototype.set = function (x, y, z, w) {
  3595. return this.copyFromFloats(x, y, z, w);
  3596. };
  3597. /**
  3598. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3599. */
  3600. Quaternion.prototype.add = function (other) {
  3601. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3602. };
  3603. /**
  3604. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3605. */
  3606. Quaternion.prototype.subtract = function (other) {
  3607. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3608. };
  3609. /**
  3610. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3611. */
  3612. Quaternion.prototype.scale = function (value) {
  3613. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3614. };
  3615. /**
  3616. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3617. */
  3618. Quaternion.prototype.multiply = function (q1) {
  3619. var result = new Quaternion(0, 0, 0, 1.0);
  3620. this.multiplyToRef(q1, result);
  3621. return result;
  3622. };
  3623. /**
  3624. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3625. * Returns the current Quaternion.
  3626. */
  3627. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3628. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3629. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3630. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3631. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3632. result.copyFromFloats(x, y, z, w);
  3633. return this;
  3634. };
  3635. /**
  3636. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3637. * Returns the updated Quaternion.
  3638. */
  3639. Quaternion.prototype.multiplyInPlace = function (q1) {
  3640. this.multiplyToRef(q1, this);
  3641. return this;
  3642. };
  3643. /**
  3644. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3645. * Returns the current Quaternion.
  3646. */
  3647. Quaternion.prototype.conjugateToRef = function (ref) {
  3648. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3649. return this;
  3650. };
  3651. /**
  3652. * Conjugates in place the current Quaternion.
  3653. * Returns the updated Quaternion.
  3654. */
  3655. Quaternion.prototype.conjugateInPlace = function () {
  3656. this.x *= -1;
  3657. this.y *= -1;
  3658. this.z *= -1;
  3659. return this;
  3660. };
  3661. /**
  3662. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3663. */
  3664. Quaternion.prototype.conjugate = function () {
  3665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3666. return result;
  3667. };
  3668. /**
  3669. * Returns the Quaternion length (float).
  3670. */
  3671. Quaternion.prototype.length = function () {
  3672. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3673. };
  3674. /**
  3675. * Normalize in place the current Quaternion.
  3676. * Returns the updated Quaternion.
  3677. */
  3678. Quaternion.prototype.normalize = function () {
  3679. var length = 1.0 / this.length();
  3680. this.x *= length;
  3681. this.y *= length;
  3682. this.z *= length;
  3683. this.w *= length;
  3684. return this;
  3685. };
  3686. /**
  3687. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3688. */
  3689. Quaternion.prototype.toEulerAngles = function (order) {
  3690. if (order === void 0) { order = "YZX"; }
  3691. var result = Vector3.Zero();
  3692. this.toEulerAnglesToRef(result, order);
  3693. return result;
  3694. };
  3695. /**
  3696. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3697. * Returns the current Quaternion.
  3698. */
  3699. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3700. if (order === void 0) { order = "YZX"; }
  3701. var qz = this.z;
  3702. var qx = this.x;
  3703. var qy = this.y;
  3704. var qw = this.w;
  3705. var sqw = qw * qw;
  3706. var sqz = qz * qz;
  3707. var sqx = qx * qx;
  3708. var sqy = qy * qy;
  3709. var zAxisY = qy * qz - qx * qw;
  3710. var limit = .4999999;
  3711. if (zAxisY < -limit) {
  3712. result.y = 2 * Math.atan2(qy, qw);
  3713. result.x = Math.PI / 2;
  3714. result.z = 0;
  3715. }
  3716. else if (zAxisY > limit) {
  3717. result.y = 2 * Math.atan2(qy, qw);
  3718. result.x = -Math.PI / 2;
  3719. result.z = 0;
  3720. }
  3721. else {
  3722. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3723. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3724. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3725. }
  3726. return this;
  3727. };
  3728. /**
  3729. * Updates the passed rotation matrix with the current Quaternion values.
  3730. * Returns the current Quaternion.
  3731. */
  3732. Quaternion.prototype.toRotationMatrix = function (result) {
  3733. var xx = this.x * this.x;
  3734. var yy = this.y * this.y;
  3735. var zz = this.z * this.z;
  3736. var xy = this.x * this.y;
  3737. var zw = this.z * this.w;
  3738. var zx = this.z * this.x;
  3739. var yw = this.y * this.w;
  3740. var yz = this.y * this.z;
  3741. var xw = this.x * this.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0;
  3754. result.m[12] = 0;
  3755. result.m[13] = 0;
  3756. result.m[14] = 0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. return this;
  3760. };
  3761. /**
  3762. * Updates the current Quaternion from the passed rotation matrix values.
  3763. * Returns the updated Quaternion.
  3764. */
  3765. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3766. Quaternion.FromRotationMatrixToRef(matrix, this);
  3767. return this;
  3768. };
  3769. // Statics
  3770. /**
  3771. * Returns a new Quaternion set from the passed rotation matrix values.
  3772. */
  3773. Quaternion.FromRotationMatrix = function (matrix) {
  3774. var result = new Quaternion();
  3775. Quaternion.FromRotationMatrixToRef(matrix, result);
  3776. return result;
  3777. };
  3778. /**
  3779. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3780. */
  3781. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3782. var data = matrix.m;
  3783. var m11 = data[0], m12 = data[4], m13 = data[8];
  3784. var m21 = data[1], m22 = data[5], m23 = data[9];
  3785. var m31 = data[2], m32 = data[6], m33 = data[10];
  3786. var trace = m11 + m22 + m33;
  3787. var s;
  3788. if (trace > 0) {
  3789. s = 0.5 / Math.sqrt(trace + 1.0);
  3790. result.w = 0.25 / s;
  3791. result.x = (m32 - m23) * s;
  3792. result.y = (m13 - m31) * s;
  3793. result.z = (m21 - m12) * s;
  3794. }
  3795. else if (m11 > m22 && m11 > m33) {
  3796. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3797. result.w = (m32 - m23) / s;
  3798. result.x = 0.25 * s;
  3799. result.y = (m12 + m21) / s;
  3800. result.z = (m13 + m31) / s;
  3801. }
  3802. else if (m22 > m33) {
  3803. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3804. result.w = (m13 - m31) / s;
  3805. result.x = (m12 + m21) / s;
  3806. result.y = 0.25 * s;
  3807. result.z = (m23 + m32) / s;
  3808. }
  3809. else {
  3810. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3811. result.w = (m21 - m12) / s;
  3812. result.x = (m13 + m31) / s;
  3813. result.y = (m23 + m32) / s;
  3814. result.z = 0.25 * s;
  3815. }
  3816. };
  3817. /**
  3818. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3819. */
  3820. Quaternion.Zero = function () {
  3821. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3822. };
  3823. /**
  3824. * Returns a new Quaternion as the inverted current Quaternion.
  3825. */
  3826. Quaternion.Inverse = function (q) {
  3827. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3828. };
  3829. /**
  3830. * Returns the identity Quaternion.
  3831. */
  3832. Quaternion.Identity = function () {
  3833. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3834. };
  3835. Quaternion.IsIdentity = function (quaternion) {
  3836. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3837. };
  3838. /**
  3839. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3840. */
  3841. Quaternion.RotationAxis = function (axis, angle) {
  3842. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3843. };
  3844. /**
  3845. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3846. */
  3847. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3848. var sin = Math.sin(angle / 2);
  3849. axis.normalize();
  3850. result.w = Math.cos(angle / 2);
  3851. result.x = axis.x * sin;
  3852. result.y = axis.y * sin;
  3853. result.z = axis.z * sin;
  3854. return result;
  3855. };
  3856. /**
  3857. * Retuns a new Quaternion set from the starting index of the passed array.
  3858. */
  3859. Quaternion.FromArray = function (array, offset) {
  3860. if (!offset) {
  3861. offset = 0;
  3862. }
  3863. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3864. };
  3865. /**
  3866. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3867. */
  3868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3869. var q = new Quaternion();
  3870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3871. return q;
  3872. };
  3873. /**
  3874. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3875. */
  3876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3878. var halfRoll = roll * 0.5;
  3879. var halfPitch = pitch * 0.5;
  3880. var halfYaw = yaw * 0.5;
  3881. var sinRoll = Math.sin(halfRoll);
  3882. var cosRoll = Math.cos(halfRoll);
  3883. var sinPitch = Math.sin(halfPitch);
  3884. var cosPitch = Math.cos(halfPitch);
  3885. var sinYaw = Math.sin(halfYaw);
  3886. var cosYaw = Math.cos(halfYaw);
  3887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3891. };
  3892. /**
  3893. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3894. */
  3895. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3896. var result = new Quaternion();
  3897. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3898. return result;
  3899. };
  3900. /**
  3901. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3902. */
  3903. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3904. // Produces a quaternion from Euler angles in the z-x-z orientation
  3905. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3906. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3907. var halfBeta = beta * 0.5;
  3908. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3909. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3910. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3911. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3912. };
  3913. /**
  3914. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3915. * cf to Vector3.RotationFromAxis() documentation.
  3916. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3917. */
  3918. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3919. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3920. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3921. return quat;
  3922. };
  3923. /**
  3924. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3925. * cf to Vector3.RotationFromAxis() documentation.
  3926. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3927. */
  3928. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3929. var rotMat = MathTmp.Matrix[0];
  3930. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3931. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3932. };
  3933. Quaternion.Slerp = function (left, right, amount) {
  3934. var result = Quaternion.Identity();
  3935. Quaternion.SlerpToRef(left, right, amount, result);
  3936. return result;
  3937. };
  3938. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3939. var num2;
  3940. var num3;
  3941. var num = amount;
  3942. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3943. var flag = false;
  3944. if (num4 < 0) {
  3945. flag = true;
  3946. num4 = -num4;
  3947. }
  3948. if (num4 > 0.999999) {
  3949. num3 = 1 - num;
  3950. num2 = flag ? -num : num;
  3951. }
  3952. else {
  3953. var num5 = Math.acos(num4);
  3954. var num6 = (1.0 / Math.sin(num5));
  3955. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3956. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3957. }
  3958. result.x = (num3 * left.x) + (num2 * right.x);
  3959. result.y = (num3 * left.y) + (num2 * right.y);
  3960. result.z = (num3 * left.z) + (num2 * right.z);
  3961. result.w = (num3 * left.w) + (num2 * right.w);
  3962. };
  3963. /**
  3964. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3965. */
  3966. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3967. var squared = amount * amount;
  3968. var cubed = amount * squared;
  3969. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3970. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3971. var part3 = (cubed - (2.0 * squared)) + amount;
  3972. var part4 = cubed - squared;
  3973. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3974. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3975. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3976. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3977. return new Quaternion(x, y, z, w);
  3978. };
  3979. return Quaternion;
  3980. }());
  3981. BABYLON.Quaternion = Quaternion;
  3982. var Matrix = /** @class */ (function () {
  3983. function Matrix() {
  3984. this._isIdentity = false;
  3985. this._isIdentityDirty = true;
  3986. this.m = new Float32Array(16);
  3987. this._markAsUpdated();
  3988. }
  3989. Matrix.prototype._markAsUpdated = function () {
  3990. this.updateFlag = Matrix._updateFlagSeed++;
  3991. this._isIdentityDirty = true;
  3992. };
  3993. // Properties
  3994. /**
  3995. * Boolean : True is the matrix is the identity matrix
  3996. */
  3997. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3998. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3999. if (this._isIdentityDirty) {
  4000. this._isIdentityDirty = false;
  4001. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4002. this._isIdentity = false;
  4003. }
  4004. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4005. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4006. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4007. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4008. this._isIdentity = false;
  4009. }
  4010. else {
  4011. this._isIdentity = true;
  4012. }
  4013. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4014. this._isIdentity = false;
  4015. }
  4016. }
  4017. return this._isIdentity;
  4018. };
  4019. /**
  4020. * Returns the matrix determinant (float).
  4021. */
  4022. Matrix.prototype.determinant = function () {
  4023. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4024. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4025. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4026. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4027. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4028. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4029. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4030. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4031. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4032. };
  4033. // Methods
  4034. /**
  4035. * Returns the matrix underlying array.
  4036. */
  4037. Matrix.prototype.toArray = function () {
  4038. return this.m;
  4039. };
  4040. /**
  4041. * Returns the matrix underlying array.
  4042. */
  4043. Matrix.prototype.asArray = function () {
  4044. return this.toArray();
  4045. };
  4046. /**
  4047. * Inverts in place the Matrix.
  4048. * Returns the Matrix inverted.
  4049. */
  4050. Matrix.prototype.invert = function () {
  4051. this.invertToRef(this);
  4052. return this;
  4053. };
  4054. /**
  4055. * Sets all the matrix elements to zero.
  4056. * Returns the Matrix.
  4057. */
  4058. Matrix.prototype.reset = function () {
  4059. for (var index = 0; index < 16; index++) {
  4060. this.m[index] = 0.0;
  4061. }
  4062. this._markAsUpdated();
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4067. */
  4068. Matrix.prototype.add = function (other) {
  4069. var result = new Matrix();
  4070. this.addToRef(other, result);
  4071. return result;
  4072. };
  4073. /**
  4074. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4075. * Returns the Matrix.
  4076. */
  4077. Matrix.prototype.addToRef = function (other, result) {
  4078. for (var index = 0; index < 16; index++) {
  4079. result.m[index] = this.m[index] + other.m[index];
  4080. }
  4081. result._markAsUpdated();
  4082. return this;
  4083. };
  4084. /**
  4085. * Adds in place the passed matrix to the current Matrix.
  4086. * Returns the updated Matrix.
  4087. */
  4088. Matrix.prototype.addToSelf = function (other) {
  4089. for (var index = 0; index < 16; index++) {
  4090. this.m[index] += other.m[index];
  4091. }
  4092. this._markAsUpdated();
  4093. return this;
  4094. };
  4095. /**
  4096. * Sets the passed matrix with the current inverted Matrix.
  4097. * Returns the unmodified current Matrix.
  4098. */
  4099. Matrix.prototype.invertToRef = function (other) {
  4100. var l1 = this.m[0];
  4101. var l2 = this.m[1];
  4102. var l3 = this.m[2];
  4103. var l4 = this.m[3];
  4104. var l5 = this.m[4];
  4105. var l6 = this.m[5];
  4106. var l7 = this.m[6];
  4107. var l8 = this.m[7];
  4108. var l9 = this.m[8];
  4109. var l10 = this.m[9];
  4110. var l11 = this.m[10];
  4111. var l12 = this.m[11];
  4112. var l13 = this.m[12];
  4113. var l14 = this.m[13];
  4114. var l15 = this.m[14];
  4115. var l16 = this.m[15];
  4116. var l17 = (l11 * l16) - (l12 * l15);
  4117. var l18 = (l10 * l16) - (l12 * l14);
  4118. var l19 = (l10 * l15) - (l11 * l14);
  4119. var l20 = (l9 * l16) - (l12 * l13);
  4120. var l21 = (l9 * l15) - (l11 * l13);
  4121. var l22 = (l9 * l14) - (l10 * l13);
  4122. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4123. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4124. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4125. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4126. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4127. var l28 = (l7 * l16) - (l8 * l15);
  4128. var l29 = (l6 * l16) - (l8 * l14);
  4129. var l30 = (l6 * l15) - (l7 * l14);
  4130. var l31 = (l5 * l16) - (l8 * l13);
  4131. var l32 = (l5 * l15) - (l7 * l13);
  4132. var l33 = (l5 * l14) - (l6 * l13);
  4133. var l34 = (l7 * l12) - (l8 * l11);
  4134. var l35 = (l6 * l12) - (l8 * l10);
  4135. var l36 = (l6 * l11) - (l7 * l10);
  4136. var l37 = (l5 * l12) - (l8 * l9);
  4137. var l38 = (l5 * l11) - (l7 * l9);
  4138. var l39 = (l5 * l10) - (l6 * l9);
  4139. other.m[0] = l23 * l27;
  4140. other.m[4] = l24 * l27;
  4141. other.m[8] = l25 * l27;
  4142. other.m[12] = l26 * l27;
  4143. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4144. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4145. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4146. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4147. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4148. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4149. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4150. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4151. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4152. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4153. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4154. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4155. other._markAsUpdated();
  4156. return this;
  4157. };
  4158. /**
  4159. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4160. * Returns the updated Matrix.
  4161. */
  4162. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4163. this.m[12] = x;
  4164. this.m[13] = y;
  4165. this.m[14] = z;
  4166. this._markAsUpdated();
  4167. return this;
  4168. };
  4169. /**
  4170. * Inserts the translation vector in the current Matrix.
  4171. * Returns the updated Matrix.
  4172. */
  4173. Matrix.prototype.setTranslation = function (vector3) {
  4174. this.m[12] = vector3.x;
  4175. this.m[13] = vector3.y;
  4176. this.m[14] = vector3.z;
  4177. this._markAsUpdated();
  4178. return this;
  4179. };
  4180. /**
  4181. * Returns a new Vector3 as the extracted translation from the Matrix.
  4182. */
  4183. Matrix.prototype.getTranslation = function () {
  4184. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4185. };
  4186. /**
  4187. * Fill a Vector3 with the extracted translation from the Matrix.
  4188. */
  4189. Matrix.prototype.getTranslationToRef = function (result) {
  4190. result.x = this.m[12];
  4191. result.y = this.m[13];
  4192. result.z = this.m[14];
  4193. return this;
  4194. };
  4195. /**
  4196. * Remove rotation and scaling part from the Matrix.
  4197. * Returns the updated Matrix.
  4198. */
  4199. Matrix.prototype.removeRotationAndScaling = function () {
  4200. this.setRowFromFloats(0, 1, 0, 0, 0);
  4201. this.setRowFromFloats(1, 0, 1, 0, 0);
  4202. this.setRowFromFloats(2, 0, 0, 1, 0);
  4203. return this;
  4204. };
  4205. /**
  4206. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4207. */
  4208. Matrix.prototype.multiply = function (other) {
  4209. var result = new Matrix();
  4210. this.multiplyToRef(other, result);
  4211. return result;
  4212. };
  4213. /**
  4214. * Updates the current Matrix from the passed one values.
  4215. * Returns the updated Matrix.
  4216. */
  4217. Matrix.prototype.copyFrom = function (other) {
  4218. for (var index = 0; index < 16; index++) {
  4219. this.m[index] = other.m[index];
  4220. }
  4221. this._markAsUpdated();
  4222. return this;
  4223. };
  4224. /**
  4225. * Populates the passed array from the starting index with the Matrix values.
  4226. * Returns the Matrix.
  4227. */
  4228. Matrix.prototype.copyToArray = function (array, offset) {
  4229. if (offset === void 0) { offset = 0; }
  4230. for (var index = 0; index < 16; index++) {
  4231. array[offset + index] = this.m[index];
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4237. */
  4238. Matrix.prototype.multiplyToRef = function (other, result) {
  4239. this.multiplyToArray(other, result.m, 0);
  4240. result._markAsUpdated();
  4241. return this;
  4242. };
  4243. /**
  4244. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4245. */
  4246. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4247. var tm0 = this.m[0];
  4248. var tm1 = this.m[1];
  4249. var tm2 = this.m[2];
  4250. var tm3 = this.m[3];
  4251. var tm4 = this.m[4];
  4252. var tm5 = this.m[5];
  4253. var tm6 = this.m[6];
  4254. var tm7 = this.m[7];
  4255. var tm8 = this.m[8];
  4256. var tm9 = this.m[9];
  4257. var tm10 = this.m[10];
  4258. var tm11 = this.m[11];
  4259. var tm12 = this.m[12];
  4260. var tm13 = this.m[13];
  4261. var tm14 = this.m[14];
  4262. var tm15 = this.m[15];
  4263. var om0 = other.m[0];
  4264. var om1 = other.m[1];
  4265. var om2 = other.m[2];
  4266. var om3 = other.m[3];
  4267. var om4 = other.m[4];
  4268. var om5 = other.m[5];
  4269. var om6 = other.m[6];
  4270. var om7 = other.m[7];
  4271. var om8 = other.m[8];
  4272. var om9 = other.m[9];
  4273. var om10 = other.m[10];
  4274. var om11 = other.m[11];
  4275. var om12 = other.m[12];
  4276. var om13 = other.m[13];
  4277. var om14 = other.m[14];
  4278. var om15 = other.m[15];
  4279. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4280. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4281. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4282. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4283. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4284. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4285. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4286. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4287. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4288. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4289. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4290. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4291. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4292. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4293. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4294. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4295. return this;
  4296. };
  4297. /**
  4298. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4299. */
  4300. Matrix.prototype.equals = function (value) {
  4301. return value &&
  4302. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4303. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4304. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4305. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4306. };
  4307. /**
  4308. * Returns a new Matrix from the current Matrix.
  4309. */
  4310. Matrix.prototype.clone = function () {
  4311. 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]);
  4312. };
  4313. /**
  4314. * Returns the string "Matrix"
  4315. */
  4316. Matrix.prototype.getClassName = function () {
  4317. return "Matrix";
  4318. };
  4319. /**
  4320. * Returns the Matrix hash code.
  4321. */
  4322. Matrix.prototype.getHashCode = function () {
  4323. var hash = this.m[0] || 0;
  4324. for (var i = 1; i < 16; i++) {
  4325. hash = (hash * 397) ^ (this.m[i] || 0);
  4326. }
  4327. return hash;
  4328. };
  4329. /**
  4330. * Decomposes the current Matrix into :
  4331. * - a scale vector3 passed as a reference to update,
  4332. * - a rotation quaternion passed as a reference to update,
  4333. * - a translation vector3 passed as a reference to update.
  4334. * Returns the true if operation was successful.
  4335. */
  4336. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4337. translation.x = this.m[12];
  4338. translation.y = this.m[13];
  4339. translation.z = this.m[14];
  4340. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4341. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4342. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4343. if (this.determinant() <= 0) {
  4344. scale.y *= -1;
  4345. }
  4346. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4347. rotation.x = 0;
  4348. rotation.y = 0;
  4349. rotation.z = 0;
  4350. rotation.w = 1;
  4351. return false;
  4352. }
  4353. 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]);
  4354. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4355. return true;
  4356. };
  4357. /**
  4358. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4359. */
  4360. Matrix.prototype.getRotationMatrix = function () {
  4361. var result = Matrix.Identity();
  4362. this.getRotationMatrixToRef(result);
  4363. return result;
  4364. };
  4365. /**
  4366. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4367. * Returns the current Matrix.
  4368. */
  4369. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4370. var m = this.m;
  4371. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4372. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4373. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4374. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4375. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4376. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4377. 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);
  4378. return this;
  4379. };
  4380. // Statics
  4381. /**
  4382. * Returns a new Matrix set from the starting index of the passed array.
  4383. */
  4384. Matrix.FromArray = function (array, offset) {
  4385. var result = new Matrix();
  4386. if (!offset) {
  4387. offset = 0;
  4388. }
  4389. Matrix.FromArrayToRef(array, offset, result);
  4390. return result;
  4391. };
  4392. /**
  4393. * Sets the passed "result" matrix from the starting index of the passed array.
  4394. */
  4395. Matrix.FromArrayToRef = function (array, offset, result) {
  4396. for (var index = 0; index < 16; index++) {
  4397. result.m[index] = array[index + offset];
  4398. }
  4399. result._markAsUpdated();
  4400. };
  4401. /**
  4402. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4403. */
  4404. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4405. for (var index = 0; index < 16; index++) {
  4406. result.m[index] = array[index + offset] * scale;
  4407. }
  4408. result._markAsUpdated();
  4409. };
  4410. /**
  4411. * Sets the passed matrix "result" with the 16 passed floats.
  4412. */
  4413. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4414. result.m[0] = initialM11;
  4415. result.m[1] = initialM12;
  4416. result.m[2] = initialM13;
  4417. result.m[3] = initialM14;
  4418. result.m[4] = initialM21;
  4419. result.m[5] = initialM22;
  4420. result.m[6] = initialM23;
  4421. result.m[7] = initialM24;
  4422. result.m[8] = initialM31;
  4423. result.m[9] = initialM32;
  4424. result.m[10] = initialM33;
  4425. result.m[11] = initialM34;
  4426. result.m[12] = initialM41;
  4427. result.m[13] = initialM42;
  4428. result.m[14] = initialM43;
  4429. result.m[15] = initialM44;
  4430. result._markAsUpdated();
  4431. };
  4432. /**
  4433. * Returns the index-th row of the current matrix as a new Vector4.
  4434. */
  4435. Matrix.prototype.getRow = function (index) {
  4436. if (index < 0 || index > 3) {
  4437. return null;
  4438. }
  4439. var i = index * 4;
  4440. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4441. };
  4442. /**
  4443. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4444. * Returns the updated Matrix.
  4445. */
  4446. Matrix.prototype.setRow = function (index, row) {
  4447. if (index < 0 || index > 3) {
  4448. return this;
  4449. }
  4450. var i = index * 4;
  4451. this.m[i + 0] = row.x;
  4452. this.m[i + 1] = row.y;
  4453. this.m[i + 2] = row.z;
  4454. this.m[i + 3] = row.w;
  4455. this._markAsUpdated();
  4456. return this;
  4457. };
  4458. /**
  4459. * Compute the transpose of the matrix.
  4460. * Returns a new Matrix.
  4461. */
  4462. Matrix.prototype.transpose = function () {
  4463. return Matrix.Transpose(this);
  4464. };
  4465. /**
  4466. * Compute the transpose of the matrix.
  4467. * Returns the current matrix.
  4468. */
  4469. Matrix.prototype.transposeToRef = function (result) {
  4470. Matrix.TransposeToRef(this, result);
  4471. return this;
  4472. };
  4473. /**
  4474. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4475. * Returns the updated Matrix.
  4476. */
  4477. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4478. if (index < 0 || index > 3) {
  4479. return this;
  4480. }
  4481. var i = index * 4;
  4482. this.m[i + 0] = x;
  4483. this.m[i + 1] = y;
  4484. this.m[i + 2] = z;
  4485. this.m[i + 3] = w;
  4486. this._markAsUpdated();
  4487. return this;
  4488. };
  4489. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4490. /**
  4491. * Static identity matrix to be used as readonly matrix
  4492. * Must not be updated.
  4493. */
  4494. get: function () {
  4495. return Matrix._identityReadOnly;
  4496. },
  4497. enumerable: true,
  4498. configurable: true
  4499. });
  4500. /**
  4501. * Returns a new Matrix set from the 16 passed floats.
  4502. */
  4503. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4504. var result = new Matrix();
  4505. result.m[0] = initialM11;
  4506. result.m[1] = initialM12;
  4507. result.m[2] = initialM13;
  4508. result.m[3] = initialM14;
  4509. result.m[4] = initialM21;
  4510. result.m[5] = initialM22;
  4511. result.m[6] = initialM23;
  4512. result.m[7] = initialM24;
  4513. result.m[8] = initialM31;
  4514. result.m[9] = initialM32;
  4515. result.m[10] = initialM33;
  4516. result.m[11] = initialM34;
  4517. result.m[12] = initialM41;
  4518. result.m[13] = initialM42;
  4519. result.m[14] = initialM43;
  4520. result.m[15] = initialM44;
  4521. return result;
  4522. };
  4523. /**
  4524. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4525. */
  4526. Matrix.Compose = function (scale, rotation, translation) {
  4527. var result = Matrix.Identity();
  4528. Matrix.ComposeToRef(scale, rotation, translation, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4533. */
  4534. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4535. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4536. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4537. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4538. result.setTranslation(translation);
  4539. };
  4540. /**
  4541. * Returns a new indentity Matrix.
  4542. */
  4543. Matrix.Identity = function () {
  4544. 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);
  4545. };
  4546. /**
  4547. * Sets the passed "result" as an identity matrix.
  4548. */
  4549. Matrix.IdentityToRef = function (result) {
  4550. 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);
  4551. };
  4552. /**
  4553. * Returns a new zero Matrix.
  4554. */
  4555. Matrix.Zero = function () {
  4556. 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);
  4557. };
  4558. /**
  4559. * Returns a new rotation matrix for "angle" radians around the X axis.
  4560. */
  4561. Matrix.RotationX = function (angle) {
  4562. var result = new Matrix();
  4563. Matrix.RotationXToRef(angle, result);
  4564. return result;
  4565. };
  4566. /**
  4567. * Returns a new Matrix as the passed inverted one.
  4568. */
  4569. Matrix.Invert = function (source) {
  4570. var result = new Matrix();
  4571. source.invertToRef(result);
  4572. return result;
  4573. };
  4574. /**
  4575. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4576. */
  4577. Matrix.RotationXToRef = function (angle, result) {
  4578. var s = Math.sin(angle);
  4579. var c = Math.cos(angle);
  4580. result.m[0] = 1.0;
  4581. result.m[15] = 1.0;
  4582. result.m[5] = c;
  4583. result.m[10] = c;
  4584. result.m[9] = -s;
  4585. result.m[6] = s;
  4586. result.m[1] = 0.0;
  4587. result.m[2] = 0.0;
  4588. result.m[3] = 0.0;
  4589. result.m[4] = 0.0;
  4590. result.m[7] = 0.0;
  4591. result.m[8] = 0.0;
  4592. result.m[11] = 0.0;
  4593. result.m[12] = 0.0;
  4594. result.m[13] = 0.0;
  4595. result.m[14] = 0.0;
  4596. result._markAsUpdated();
  4597. };
  4598. /**
  4599. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4600. */
  4601. Matrix.RotationY = function (angle) {
  4602. var result = new Matrix();
  4603. Matrix.RotationYToRef(angle, result);
  4604. return result;
  4605. };
  4606. /**
  4607. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4608. */
  4609. Matrix.RotationYToRef = function (angle, result) {
  4610. var s = Math.sin(angle);
  4611. var c = Math.cos(angle);
  4612. result.m[5] = 1.0;
  4613. result.m[15] = 1.0;
  4614. result.m[0] = c;
  4615. result.m[2] = -s;
  4616. result.m[8] = s;
  4617. result.m[10] = c;
  4618. result.m[1] = 0.0;
  4619. result.m[3] = 0.0;
  4620. result.m[4] = 0.0;
  4621. result.m[6] = 0.0;
  4622. result.m[7] = 0.0;
  4623. result.m[9] = 0.0;
  4624. result.m[11] = 0.0;
  4625. result.m[12] = 0.0;
  4626. result.m[13] = 0.0;
  4627. result.m[14] = 0.0;
  4628. result._markAsUpdated();
  4629. };
  4630. /**
  4631. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4632. */
  4633. Matrix.RotationZ = function (angle) {
  4634. var result = new Matrix();
  4635. Matrix.RotationZToRef(angle, result);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4640. */
  4641. Matrix.RotationZToRef = function (angle, result) {
  4642. var s = Math.sin(angle);
  4643. var c = Math.cos(angle);
  4644. result.m[10] = 1.0;
  4645. result.m[15] = 1.0;
  4646. result.m[0] = c;
  4647. result.m[1] = s;
  4648. result.m[4] = -s;
  4649. result.m[5] = c;
  4650. result.m[2] = 0.0;
  4651. result.m[3] = 0.0;
  4652. result.m[6] = 0.0;
  4653. result.m[7] = 0.0;
  4654. result.m[8] = 0.0;
  4655. result.m[9] = 0.0;
  4656. result.m[11] = 0.0;
  4657. result.m[12] = 0.0;
  4658. result.m[13] = 0.0;
  4659. result.m[14] = 0.0;
  4660. result._markAsUpdated();
  4661. };
  4662. /**
  4663. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4664. */
  4665. Matrix.RotationAxis = function (axis, angle) {
  4666. var result = Matrix.Zero();
  4667. Matrix.RotationAxisToRef(axis, angle, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4672. */
  4673. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4674. var s = Math.sin(-angle);
  4675. var c = Math.cos(-angle);
  4676. var c1 = 1 - c;
  4677. axis.normalize();
  4678. result.m[0] = (axis.x * axis.x) * c1 + c;
  4679. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4680. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4681. result.m[3] = 0.0;
  4682. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4683. result.m[5] = (axis.y * axis.y) * c1 + c;
  4684. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4685. result.m[7] = 0.0;
  4686. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4687. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4688. result.m[10] = (axis.z * axis.z) * c1 + c;
  4689. result.m[11] = 0.0;
  4690. result.m[15] = 1.0;
  4691. result._markAsUpdated();
  4692. };
  4693. /**
  4694. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4695. */
  4696. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4697. var result = new Matrix();
  4698. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4699. return result;
  4700. };
  4701. /**
  4702. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4703. */
  4704. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4705. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4706. this._tempQuaternion.toRotationMatrix(result);
  4707. };
  4708. /**
  4709. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4710. */
  4711. Matrix.Scaling = function (x, y, z) {
  4712. var result = Matrix.Zero();
  4713. Matrix.ScalingToRef(x, y, z, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4718. */
  4719. Matrix.ScalingToRef = function (x, y, z, result) {
  4720. result.m[0] = x;
  4721. result.m[1] = 0.0;
  4722. result.m[2] = 0.0;
  4723. result.m[3] = 0.0;
  4724. result.m[4] = 0.0;
  4725. result.m[5] = y;
  4726. result.m[6] = 0.0;
  4727. result.m[7] = 0.0;
  4728. result.m[8] = 0.0;
  4729. result.m[9] = 0.0;
  4730. result.m[10] = z;
  4731. result.m[11] = 0.0;
  4732. result.m[12] = 0.0;
  4733. result.m[13] = 0.0;
  4734. result.m[14] = 0.0;
  4735. result.m[15] = 1.0;
  4736. result._markAsUpdated();
  4737. };
  4738. /**
  4739. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4740. */
  4741. Matrix.Translation = function (x, y, z) {
  4742. var result = Matrix.Identity();
  4743. Matrix.TranslationToRef(x, y, z, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4748. */
  4749. Matrix.TranslationToRef = function (x, y, z, result) {
  4750. 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);
  4751. };
  4752. /**
  4753. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4754. */
  4755. Matrix.Lerp = function (startValue, endValue, gradient) {
  4756. var result = Matrix.Zero();
  4757. for (var index = 0; index < 16; index++) {
  4758. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4759. }
  4760. result._markAsUpdated();
  4761. return result;
  4762. };
  4763. /**
  4764. * Returns a new Matrix whose values are computed by :
  4765. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4766. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4767. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4768. */
  4769. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4770. var startScale = new Vector3(0, 0, 0);
  4771. var startRotation = new Quaternion();
  4772. var startTranslation = new Vector3(0, 0, 0);
  4773. startValue.decompose(startScale, startRotation, startTranslation);
  4774. var endScale = new Vector3(0, 0, 0);
  4775. var endRotation = new Quaternion();
  4776. var endTranslation = new Vector3(0, 0, 0);
  4777. endValue.decompose(endScale, endRotation, endTranslation);
  4778. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4779. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4780. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4781. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4782. };
  4783. /**
  4784. * 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".
  4785. * This methods works for a Left-Handed system.
  4786. */
  4787. Matrix.LookAtLH = function (eye, target, up) {
  4788. var result = Matrix.Zero();
  4789. Matrix.LookAtLHToRef(eye, target, up, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * 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".
  4794. * This methods works for a Left-Handed system.
  4795. */
  4796. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4797. // Z axis
  4798. target.subtractToRef(eye, this._zAxis);
  4799. this._zAxis.normalize();
  4800. // X axis
  4801. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4802. if (this._xAxis.lengthSquared() === 0) {
  4803. this._xAxis.x = 1.0;
  4804. }
  4805. else {
  4806. this._xAxis.normalize();
  4807. }
  4808. // Y axis
  4809. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4810. this._yAxis.normalize();
  4811. // Eye angles
  4812. var ex = -Vector3.Dot(this._xAxis, eye);
  4813. var ey = -Vector3.Dot(this._yAxis, eye);
  4814. var ez = -Vector3.Dot(this._zAxis, eye);
  4815. 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);
  4816. };
  4817. /**
  4818. * 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".
  4819. * This methods works for a Right-Handed system.
  4820. */
  4821. Matrix.LookAtRH = function (eye, target, up) {
  4822. var result = Matrix.Zero();
  4823. Matrix.LookAtRHToRef(eye, target, up, result);
  4824. return result;
  4825. };
  4826. /**
  4827. * 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".
  4828. * This methods works for a Left-Handed system.
  4829. */
  4830. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4831. // Z axis
  4832. eye.subtractToRef(target, this._zAxis);
  4833. this._zAxis.normalize();
  4834. // X axis
  4835. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4836. if (this._xAxis.lengthSquared() === 0) {
  4837. this._xAxis.x = 1.0;
  4838. }
  4839. else {
  4840. this._xAxis.normalize();
  4841. }
  4842. // Y axis
  4843. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4844. this._yAxis.normalize();
  4845. // Eye angles
  4846. var ex = -Vector3.Dot(this._xAxis, eye);
  4847. var ey = -Vector3.Dot(this._yAxis, eye);
  4848. var ez = -Vector3.Dot(this._zAxis, eye);
  4849. 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);
  4850. };
  4851. /**
  4852. * 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.
  4853. */
  4854. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4855. var matrix = Matrix.Zero();
  4856. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4857. return matrix;
  4858. };
  4859. /**
  4860. * 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.
  4861. */
  4862. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4863. var n = znear;
  4864. var f = zfar;
  4865. var a = 2.0 / width;
  4866. var b = 2.0 / height;
  4867. var c = 2.0 / (f - n);
  4868. var d = -(f + n) / (f - n);
  4869. 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);
  4870. };
  4871. /**
  4872. * 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.
  4873. */
  4874. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4875. var matrix = Matrix.Zero();
  4876. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4877. return matrix;
  4878. };
  4879. /**
  4880. * 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.
  4881. */
  4882. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4883. var n = znear;
  4884. var f = zfar;
  4885. var a = 2.0 / (right - left);
  4886. var b = 2.0 / (top - bottom);
  4887. var c = 2.0 / (f - n);
  4888. var d = -(f + n) / (f - n);
  4889. var i0 = (left + right) / (left - right);
  4890. var i1 = (top + bottom) / (bottom - top);
  4891. 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);
  4892. };
  4893. /**
  4894. * 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.
  4895. */
  4896. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4897. var matrix = Matrix.Zero();
  4898. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4899. return matrix;
  4900. };
  4901. /**
  4902. * 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.
  4903. */
  4904. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4905. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4906. result.m[10] *= -1.0;
  4907. };
  4908. /**
  4909. * 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.
  4910. */
  4911. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4912. var matrix = Matrix.Zero();
  4913. var n = znear;
  4914. var f = zfar;
  4915. var a = 2.0 * n / width;
  4916. var b = 2.0 * n / height;
  4917. var c = (f + n) / (f - n);
  4918. var d = -2.0 * f * n / (f - n);
  4919. 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);
  4920. return matrix;
  4921. };
  4922. /**
  4923. * 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.
  4924. */
  4925. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4928. return matrix;
  4929. };
  4930. /**
  4931. * 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.
  4932. */
  4933. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4934. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4935. var n = znear;
  4936. var f = zfar;
  4937. var t = 1.0 / (Math.tan(fov * 0.5));
  4938. var a = isVerticalFovFixed ? (t / aspect) : t;
  4939. var b = isVerticalFovFixed ? t : (t * aspect);
  4940. var c = (f + n) / (f - n);
  4941. var d = -2.0 * f * n / (f - n);
  4942. 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);
  4943. };
  4944. /**
  4945. * 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.
  4946. */
  4947. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4948. var matrix = Matrix.Zero();
  4949. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4950. return matrix;
  4951. };
  4952. /**
  4953. * 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.
  4954. */
  4955. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4956. //alternatively this could be expressed as:
  4957. // m = PerspectiveFovLHToRef
  4958. // m[10] *= -1.0;
  4959. // m[11] *= -1.0;
  4960. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4961. var n = znear;
  4962. var f = zfar;
  4963. var t = 1.0 / (Math.tan(fov * 0.5));
  4964. var a = isVerticalFovFixed ? (t / aspect) : t;
  4965. var b = isVerticalFovFixed ? t : (t * aspect);
  4966. var c = -(f + n) / (f - n);
  4967. var d = -2 * f * n / (f - n);
  4968. 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);
  4969. };
  4970. /**
  4971. * 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.
  4972. */
  4973. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4974. if (rightHanded === void 0) { rightHanded = false; }
  4975. var rightHandedFactor = rightHanded ? -1 : 1;
  4976. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4977. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4978. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4979. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4980. var xScale = 2.0 / (leftTan + rightTan);
  4981. var yScale = 2.0 / (upTan + downTan);
  4982. result.m[0] = xScale;
  4983. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4984. result.m[5] = yScale;
  4985. result.m[6] = result.m[7] = 0.0;
  4986. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4987. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4988. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4989. result.m[10] = -zfar / (znear - zfar);
  4990. result.m[11] = 1.0 * rightHandedFactor;
  4991. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4992. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4993. // result.m[14] = (znear * zfar) / (znear - zfar);
  4994. result._markAsUpdated();
  4995. };
  4996. /**
  4997. * Returns the final transformation matrix : world * view * projection * viewport
  4998. */
  4999. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5000. var cw = viewport.width;
  5001. var ch = viewport.height;
  5002. var cx = viewport.x;
  5003. var cy = viewport.y;
  5004. 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);
  5005. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5006. };
  5007. /**
  5008. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5009. */
  5010. Matrix.GetAsMatrix2x2 = function (matrix) {
  5011. return new Float32Array([
  5012. matrix.m[0], matrix.m[1],
  5013. matrix.m[4], matrix.m[5]
  5014. ]);
  5015. };
  5016. /**
  5017. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5018. */
  5019. Matrix.GetAsMatrix3x3 = function (matrix) {
  5020. return new Float32Array([
  5021. matrix.m[0], matrix.m[1], matrix.m[2],
  5022. matrix.m[4], matrix.m[5], matrix.m[6],
  5023. matrix.m[8], matrix.m[9], matrix.m[10]
  5024. ]);
  5025. };
  5026. /**
  5027. * Compute the transpose of the passed Matrix.
  5028. * Returns a new Matrix.
  5029. */
  5030. Matrix.Transpose = function (matrix) {
  5031. var result = new Matrix();
  5032. Matrix.TransposeToRef(matrix, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5037. */
  5038. Matrix.TransposeToRef = function (matrix, result) {
  5039. result.m[0] = matrix.m[0];
  5040. result.m[1] = matrix.m[4];
  5041. result.m[2] = matrix.m[8];
  5042. result.m[3] = matrix.m[12];
  5043. result.m[4] = matrix.m[1];
  5044. result.m[5] = matrix.m[5];
  5045. result.m[6] = matrix.m[9];
  5046. result.m[7] = matrix.m[13];
  5047. result.m[8] = matrix.m[2];
  5048. result.m[9] = matrix.m[6];
  5049. result.m[10] = matrix.m[10];
  5050. result.m[11] = matrix.m[14];
  5051. result.m[12] = matrix.m[3];
  5052. result.m[13] = matrix.m[7];
  5053. result.m[14] = matrix.m[11];
  5054. result.m[15] = matrix.m[15];
  5055. };
  5056. /**
  5057. * Returns a new Matrix as the reflection matrix across the passed plane.
  5058. */
  5059. Matrix.Reflection = function (plane) {
  5060. var matrix = new Matrix();
  5061. Matrix.ReflectionToRef(plane, matrix);
  5062. return matrix;
  5063. };
  5064. /**
  5065. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5066. */
  5067. Matrix.ReflectionToRef = function (plane, result) {
  5068. plane.normalize();
  5069. var x = plane.normal.x;
  5070. var y = plane.normal.y;
  5071. var z = plane.normal.z;
  5072. var temp = -2 * x;
  5073. var temp2 = -2 * y;
  5074. var temp3 = -2 * z;
  5075. result.m[0] = (temp * x) + 1;
  5076. result.m[1] = temp2 * x;
  5077. result.m[2] = temp3 * x;
  5078. result.m[3] = 0.0;
  5079. result.m[4] = temp * y;
  5080. result.m[5] = (temp2 * y) + 1;
  5081. result.m[6] = temp3 * y;
  5082. result.m[7] = 0.0;
  5083. result.m[8] = temp * z;
  5084. result.m[9] = temp2 * z;
  5085. result.m[10] = (temp3 * z) + 1;
  5086. result.m[11] = 0.0;
  5087. result.m[12] = temp * plane.d;
  5088. result.m[13] = temp2 * plane.d;
  5089. result.m[14] = temp3 * plane.d;
  5090. result.m[15] = 1.0;
  5091. result._markAsUpdated();
  5092. };
  5093. /**
  5094. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5095. */
  5096. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5097. result.m[0] = xaxis.x;
  5098. result.m[1] = xaxis.y;
  5099. result.m[2] = xaxis.z;
  5100. result.m[3] = 0.0;
  5101. result.m[4] = yaxis.x;
  5102. result.m[5] = yaxis.y;
  5103. result.m[6] = yaxis.z;
  5104. result.m[7] = 0.0;
  5105. result.m[8] = zaxis.x;
  5106. result.m[9] = zaxis.y;
  5107. result.m[10] = zaxis.z;
  5108. result.m[11] = 0.0;
  5109. result.m[12] = 0.0;
  5110. result.m[13] = 0.0;
  5111. result.m[14] = 0.0;
  5112. result.m[15] = 1.0;
  5113. result._markAsUpdated();
  5114. };
  5115. /**
  5116. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5117. */
  5118. Matrix.FromQuaternionToRef = function (quat, result) {
  5119. var xx = quat.x * quat.x;
  5120. var yy = quat.y * quat.y;
  5121. var zz = quat.z * quat.z;
  5122. var xy = quat.x * quat.y;
  5123. var zw = quat.z * quat.w;
  5124. var zx = quat.z * quat.x;
  5125. var yw = quat.y * quat.w;
  5126. var yz = quat.y * quat.z;
  5127. var xw = quat.x * quat.w;
  5128. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5129. result.m[1] = 2.0 * (xy + zw);
  5130. result.m[2] = 2.0 * (zx - yw);
  5131. result.m[3] = 0.0;
  5132. result.m[4] = 2.0 * (xy - zw);
  5133. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5134. result.m[6] = 2.0 * (yz + xw);
  5135. result.m[7] = 0.0;
  5136. result.m[8] = 2.0 * (zx + yw);
  5137. result.m[9] = 2.0 * (yz - xw);
  5138. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5139. result.m[11] = 0.0;
  5140. result.m[12] = 0.0;
  5141. result.m[13] = 0.0;
  5142. result.m[14] = 0.0;
  5143. result.m[15] = 1.0;
  5144. result._markAsUpdated();
  5145. };
  5146. Matrix._tempQuaternion = new Quaternion();
  5147. Matrix._xAxis = Vector3.Zero();
  5148. Matrix._yAxis = Vector3.Zero();
  5149. Matrix._zAxis = Vector3.Zero();
  5150. Matrix._updateFlagSeed = 0;
  5151. Matrix._identityReadOnly = Matrix.Identity();
  5152. return Matrix;
  5153. }());
  5154. BABYLON.Matrix = Matrix;
  5155. var Plane = /** @class */ (function () {
  5156. /**
  5157. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5158. */
  5159. function Plane(a, b, c, d) {
  5160. this.normal = new Vector3(a, b, c);
  5161. this.d = d;
  5162. }
  5163. /**
  5164. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5165. */
  5166. Plane.prototype.asArray = function () {
  5167. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5168. };
  5169. // Methods
  5170. /**
  5171. * Returns a new plane copied from the current Plane.
  5172. */
  5173. Plane.prototype.clone = function () {
  5174. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5175. };
  5176. /**
  5177. * Returns the string "Plane".
  5178. */
  5179. Plane.prototype.getClassName = function () {
  5180. return "Plane";
  5181. };
  5182. /**
  5183. * Returns the Plane hash code.
  5184. */
  5185. Plane.prototype.getHashCode = function () {
  5186. var hash = this.normal.getHashCode();
  5187. hash = (hash * 397) ^ (this.d || 0);
  5188. return hash;
  5189. };
  5190. /**
  5191. * Normalize the current Plane in place.
  5192. * Returns the updated Plane.
  5193. */
  5194. Plane.prototype.normalize = function () {
  5195. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5196. var magnitude = 0.0;
  5197. if (norm !== 0) {
  5198. magnitude = 1.0 / norm;
  5199. }
  5200. this.normal.x *= magnitude;
  5201. this.normal.y *= magnitude;
  5202. this.normal.z *= magnitude;
  5203. this.d *= magnitude;
  5204. return this;
  5205. };
  5206. /**
  5207. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5208. */
  5209. Plane.prototype.transform = function (transformation) {
  5210. var transposedMatrix = Matrix.Transpose(transformation);
  5211. var x = this.normal.x;
  5212. var y = this.normal.y;
  5213. var z = this.normal.z;
  5214. var d = this.d;
  5215. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5216. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5217. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5218. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5219. return new Plane(normalX, normalY, normalZ, finalD);
  5220. };
  5221. /**
  5222. * Returns the dot product (float) of the point coordinates and the plane normal.
  5223. */
  5224. Plane.prototype.dotCoordinate = function (point) {
  5225. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5226. };
  5227. /**
  5228. * Updates the current Plane from the plane defined by the three passed points.
  5229. * Returns the updated Plane.
  5230. */
  5231. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5232. var x1 = point2.x - point1.x;
  5233. var y1 = point2.y - point1.y;
  5234. var z1 = point2.z - point1.z;
  5235. var x2 = point3.x - point1.x;
  5236. var y2 = point3.y - point1.y;
  5237. var z2 = point3.z - point1.z;
  5238. var yz = (y1 * z2) - (z1 * y2);
  5239. var xz = (z1 * x2) - (x1 * z2);
  5240. var xy = (x1 * y2) - (y1 * x2);
  5241. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5242. var invPyth;
  5243. if (pyth !== 0) {
  5244. invPyth = 1.0 / pyth;
  5245. }
  5246. else {
  5247. invPyth = 0.0;
  5248. }
  5249. this.normal.x = yz * invPyth;
  5250. this.normal.y = xz * invPyth;
  5251. this.normal.z = xy * invPyth;
  5252. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5253. return this;
  5254. };
  5255. /**
  5256. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5257. */
  5258. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5259. var dot = Vector3.Dot(this.normal, direction);
  5260. return (dot <= epsilon);
  5261. };
  5262. /**
  5263. * Returns the signed distance (float) from the passed point to the Plane.
  5264. */
  5265. Plane.prototype.signedDistanceTo = function (point) {
  5266. return Vector3.Dot(point, this.normal) + this.d;
  5267. };
  5268. // Statics
  5269. /**
  5270. * Returns a new Plane from the passed array.
  5271. */
  5272. Plane.FromArray = function (array) {
  5273. return new Plane(array[0], array[1], array[2], array[3]);
  5274. };
  5275. /**
  5276. * Returns a new Plane defined by the three passed points.
  5277. */
  5278. Plane.FromPoints = function (point1, point2, point3) {
  5279. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5280. result.copyFromPoints(point1, point2, point3);
  5281. return result;
  5282. };
  5283. /**
  5284. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5285. * Note : the vector "normal" is updated because normalized.
  5286. */
  5287. Plane.FromPositionAndNormal = function (origin, normal) {
  5288. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5289. normal.normalize();
  5290. result.normal = normal;
  5291. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5292. return result;
  5293. };
  5294. /**
  5295. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5296. */
  5297. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5298. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5299. return Vector3.Dot(point, normal) + d;
  5300. };
  5301. return Plane;
  5302. }());
  5303. BABYLON.Plane = Plane;
  5304. var Viewport = /** @class */ (function () {
  5305. /**
  5306. * Creates a Viewport object located at (x, y) and sized (width, height).
  5307. */
  5308. function Viewport(x, y, width, height) {
  5309. this.x = x;
  5310. this.y = y;
  5311. this.width = width;
  5312. this.height = height;
  5313. }
  5314. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5315. if (renderWidthOrEngine.getRenderWidth) {
  5316. var engine = renderWidthOrEngine;
  5317. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5318. }
  5319. var renderWidth = renderWidthOrEngine;
  5320. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5321. };
  5322. /**
  5323. * Returns a new Viewport copied from the current one.
  5324. */
  5325. Viewport.prototype.clone = function () {
  5326. return new Viewport(this.x, this.y, this.width, this.height);
  5327. };
  5328. return Viewport;
  5329. }());
  5330. BABYLON.Viewport = Viewport;
  5331. var Frustum = /** @class */ (function () {
  5332. function Frustum() {
  5333. }
  5334. /**
  5335. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5336. */
  5337. Frustum.GetPlanes = function (transform) {
  5338. var frustumPlanes = [];
  5339. for (var index = 0; index < 6; index++) {
  5340. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5341. }
  5342. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5343. return frustumPlanes;
  5344. };
  5345. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5346. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5347. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5348. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5349. frustumPlane.d = transform.m[15] + transform.m[14];
  5350. frustumPlane.normalize();
  5351. };
  5352. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5353. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5354. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5355. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5356. frustumPlane.d = transform.m[15] - transform.m[14];
  5357. frustumPlane.normalize();
  5358. };
  5359. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5363. frustumPlane.d = transform.m[15] + transform.m[12];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5370. frustumPlane.d = transform.m[15] - transform.m[12];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5375. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5376. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5377. frustumPlane.d = transform.m[15] - transform.m[13];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5382. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5383. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5384. frustumPlane.d = transform.m[15] + transform.m[13];
  5385. frustumPlane.normalize();
  5386. };
  5387. /**
  5388. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5389. */
  5390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5391. // Near
  5392. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5393. // Far
  5394. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5395. // Left
  5396. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5397. // Right
  5398. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5399. // Top
  5400. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5401. // Bottom
  5402. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5403. };
  5404. return Frustum;
  5405. }());
  5406. BABYLON.Frustum = Frustum;
  5407. var Space;
  5408. (function (Space) {
  5409. Space[Space["LOCAL"] = 0] = "LOCAL";
  5410. Space[Space["WORLD"] = 1] = "WORLD";
  5411. Space[Space["BONE"] = 2] = "BONE";
  5412. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5413. var Axis = /** @class */ (function () {
  5414. function Axis() {
  5415. }
  5416. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5417. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5418. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5419. return Axis;
  5420. }());
  5421. BABYLON.Axis = Axis;
  5422. ;
  5423. var BezierCurve = /** @class */ (function () {
  5424. function BezierCurve() {
  5425. }
  5426. /**
  5427. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5428. */
  5429. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5430. // Extract X (which is equal to time here)
  5431. var f0 = 1 - 3 * x2 + 3 * x1;
  5432. var f1 = 3 * x2 - 6 * x1;
  5433. var f2 = 3 * x1;
  5434. var refinedT = t;
  5435. for (var i = 0; i < 5; i++) {
  5436. var refinedT2 = refinedT * refinedT;
  5437. var refinedT3 = refinedT2 * refinedT;
  5438. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5439. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5440. refinedT -= (x - t) * slope;
  5441. refinedT = Math.min(1, Math.max(0, refinedT));
  5442. }
  5443. // Resolve cubic bezier for the given x
  5444. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5445. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5446. Math.pow(refinedT, 3);
  5447. };
  5448. return BezierCurve;
  5449. }());
  5450. BABYLON.BezierCurve = BezierCurve;
  5451. var Orientation;
  5452. (function (Orientation) {
  5453. Orientation[Orientation["CW"] = 0] = "CW";
  5454. Orientation[Orientation["CCW"] = 1] = "CCW";
  5455. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5456. var Angle = /** @class */ (function () {
  5457. /**
  5458. * Creates an Angle object of "radians" radians (float).
  5459. */
  5460. function Angle(radians) {
  5461. var _this = this;
  5462. /**
  5463. * Returns the Angle value in degrees (float).
  5464. */
  5465. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5466. /**
  5467. * Returns the Angle value in radians (float).
  5468. */
  5469. this.radians = function () { return _this._radians; };
  5470. this._radians = radians;
  5471. if (this._radians < 0.0)
  5472. this._radians += (2.0 * Math.PI);
  5473. }
  5474. /**
  5475. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5476. */
  5477. Angle.BetweenTwoPoints = function (a, b) {
  5478. var delta = b.subtract(a);
  5479. var theta = Math.atan2(delta.y, delta.x);
  5480. return new Angle(theta);
  5481. };
  5482. /**
  5483. * Returns a new Angle object from the passed float in radians.
  5484. */
  5485. Angle.FromRadians = function (radians) {
  5486. return new Angle(radians);
  5487. };
  5488. /**
  5489. * Returns a new Angle object from the passed float in degrees.
  5490. */
  5491. Angle.FromDegrees = function (degrees) {
  5492. return new Angle(degrees * Math.PI / 180.0);
  5493. };
  5494. return Angle;
  5495. }());
  5496. BABYLON.Angle = Angle;
  5497. var Arc2 = /** @class */ (function () {
  5498. /**
  5499. * Creates an Arc object from the three passed points : start, middle and end.
  5500. */
  5501. function Arc2(startPoint, midPoint, endPoint) {
  5502. this.startPoint = startPoint;
  5503. this.midPoint = midPoint;
  5504. this.endPoint = endPoint;
  5505. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5506. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5507. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5508. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5509. 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);
  5510. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5511. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5512. var a1 = this.startAngle.degrees();
  5513. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5514. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5515. // angles correction
  5516. if (a2 - a1 > +180.0)
  5517. a2 -= 360.0;
  5518. if (a2 - a1 < -180.0)
  5519. a2 += 360.0;
  5520. if (a3 - a2 > +180.0)
  5521. a3 -= 360.0;
  5522. if (a3 - a2 < -180.0)
  5523. a3 += 360.0;
  5524. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5525. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5526. }
  5527. return Arc2;
  5528. }());
  5529. BABYLON.Arc2 = Arc2;
  5530. var Path2 = /** @class */ (function () {
  5531. /**
  5532. * Creates a Path2 object from the starting 2D coordinates x and y.
  5533. */
  5534. function Path2(x, y) {
  5535. this._points = new Array();
  5536. this._length = 0.0;
  5537. this.closed = false;
  5538. this._points.push(new Vector2(x, y));
  5539. }
  5540. /**
  5541. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5542. * Returns the updated Path2.
  5543. */
  5544. Path2.prototype.addLineTo = function (x, y) {
  5545. if (this.closed) {
  5546. //Tools.Error("cannot add lines to closed paths");
  5547. return this;
  5548. }
  5549. var newPoint = new Vector2(x, y);
  5550. var previousPoint = this._points[this._points.length - 1];
  5551. this._points.push(newPoint);
  5552. this._length += newPoint.subtract(previousPoint).length();
  5553. return this;
  5554. };
  5555. /**
  5556. * 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.
  5557. * Returns the updated Path2.
  5558. */
  5559. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5560. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5561. if (this.closed) {
  5562. //Tools.Error("cannot add arcs to closed paths");
  5563. return this;
  5564. }
  5565. var startPoint = this._points[this._points.length - 1];
  5566. var midPoint = new Vector2(midX, midY);
  5567. var endPoint = new Vector2(endX, endY);
  5568. var arc = new Arc2(startPoint, midPoint, endPoint);
  5569. var increment = arc.angle.radians() / numberOfSegments;
  5570. if (arc.orientation === Orientation.CW)
  5571. increment *= -1;
  5572. var currentAngle = arc.startAngle.radians() + increment;
  5573. for (var i = 0; i < numberOfSegments; i++) {
  5574. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5575. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5576. this.addLineTo(x, y);
  5577. currentAngle += increment;
  5578. }
  5579. return this;
  5580. };
  5581. /**
  5582. * Closes the Path2.
  5583. * Returns the Path2.
  5584. */
  5585. Path2.prototype.close = function () {
  5586. this.closed = true;
  5587. return this;
  5588. };
  5589. /**
  5590. * Returns the Path2 total length (float).
  5591. */
  5592. Path2.prototype.length = function () {
  5593. var result = this._length;
  5594. if (!this.closed) {
  5595. var lastPoint = this._points[this._points.length - 1];
  5596. var firstPoint = this._points[0];
  5597. result += (firstPoint.subtract(lastPoint).length());
  5598. }
  5599. return result;
  5600. };
  5601. /**
  5602. * Returns the Path2 internal array of points.
  5603. */
  5604. Path2.prototype.getPoints = function () {
  5605. return this._points;
  5606. };
  5607. /**
  5608. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5609. */
  5610. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5611. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5612. //Tools.Error("normalized length position should be between 0 and 1.");
  5613. return Vector2.Zero();
  5614. }
  5615. var lengthPosition = normalizedLengthPosition * this.length();
  5616. var previousOffset = 0;
  5617. for (var i = 0; i < this._points.length; i++) {
  5618. var j = (i + 1) % this._points.length;
  5619. var a = this._points[i];
  5620. var b = this._points[j];
  5621. var bToA = b.subtract(a);
  5622. var nextOffset = (bToA.length() + previousOffset);
  5623. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5624. var dir = bToA.normalize();
  5625. var localOffset = lengthPosition - previousOffset;
  5626. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5627. }
  5628. previousOffset = nextOffset;
  5629. }
  5630. //Tools.Error("internal error");
  5631. return Vector2.Zero();
  5632. };
  5633. /**
  5634. * Returns a new Path2 starting at the coordinates (x, y).
  5635. */
  5636. Path2.StartingAt = function (x, y) {
  5637. return new Path2(x, y);
  5638. };
  5639. return Path2;
  5640. }());
  5641. BABYLON.Path2 = Path2;
  5642. var Path3D = /** @class */ (function () {
  5643. /**
  5644. * new Path3D(path, normal, raw)
  5645. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5646. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5647. * path : an array of Vector3, the curve axis of the Path3D
  5648. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5649. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5650. */
  5651. function Path3D(path, firstNormal, raw) {
  5652. if (firstNormal === void 0) { firstNormal = null; }
  5653. this.path = path;
  5654. this._curve = new Array();
  5655. this._distances = new Array();
  5656. this._tangents = new Array();
  5657. this._normals = new Array();
  5658. this._binormals = new Array();
  5659. for (var p = 0; p < path.length; p++) {
  5660. this._curve[p] = path[p].clone(); // hard copy
  5661. }
  5662. this._raw = raw || false;
  5663. this._compute(firstNormal);
  5664. }
  5665. /**
  5666. * Returns the Path3D array of successive Vector3 designing its curve.
  5667. */
  5668. Path3D.prototype.getCurve = function () {
  5669. return this._curve;
  5670. };
  5671. /**
  5672. * Returns an array populated with tangent vectors on each Path3D curve point.
  5673. */
  5674. Path3D.prototype.getTangents = function () {
  5675. return this._tangents;
  5676. };
  5677. /**
  5678. * Returns an array populated with normal vectors on each Path3D curve point.
  5679. */
  5680. Path3D.prototype.getNormals = function () {
  5681. return this._normals;
  5682. };
  5683. /**
  5684. * Returns an array populated with binormal vectors on each Path3D curve point.
  5685. */
  5686. Path3D.prototype.getBinormals = function () {
  5687. return this._binormals;
  5688. };
  5689. /**
  5690. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5691. */
  5692. Path3D.prototype.getDistances = function () {
  5693. return this._distances;
  5694. };
  5695. /**
  5696. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5697. * Returns the same object updated.
  5698. */
  5699. Path3D.prototype.update = function (path, firstNormal) {
  5700. if (firstNormal === void 0) { firstNormal = null; }
  5701. for (var p = 0; p < path.length; p++) {
  5702. this._curve[p].x = path[p].x;
  5703. this._curve[p].y = path[p].y;
  5704. this._curve[p].z = path[p].z;
  5705. }
  5706. this._compute(firstNormal);
  5707. return this;
  5708. };
  5709. // private function compute() : computes tangents, normals and binormals
  5710. Path3D.prototype._compute = function (firstNormal) {
  5711. var l = this._curve.length;
  5712. // first and last tangents
  5713. this._tangents[0] = this._getFirstNonNullVector(0);
  5714. if (!this._raw) {
  5715. this._tangents[0].normalize();
  5716. }
  5717. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5718. if (!this._raw) {
  5719. this._tangents[l - 1].normalize();
  5720. }
  5721. // normals and binormals at first point : arbitrary vector with _normalVector()
  5722. var tg0 = this._tangents[0];
  5723. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5724. this._normals[0] = pp0;
  5725. if (!this._raw) {
  5726. this._normals[0].normalize();
  5727. }
  5728. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5729. if (!this._raw) {
  5730. this._binormals[0].normalize();
  5731. }
  5732. this._distances[0] = 0.0;
  5733. // normals and binormals : next points
  5734. var prev; // previous vector (segment)
  5735. var cur; // current vector (segment)
  5736. var curTang; // current tangent
  5737. // previous normal
  5738. var prevBinor; // previous binormal
  5739. for (var i = 1; i < l; i++) {
  5740. // tangents
  5741. prev = this._getLastNonNullVector(i);
  5742. if (i < l - 1) {
  5743. cur = this._getFirstNonNullVector(i);
  5744. this._tangents[i] = prev.add(cur);
  5745. this._tangents[i].normalize();
  5746. }
  5747. this._distances[i] = this._distances[i - 1] + prev.length();
  5748. // normals and binormals
  5749. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5750. curTang = this._tangents[i];
  5751. prevBinor = this._binormals[i - 1];
  5752. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5753. if (!this._raw) {
  5754. this._normals[i].normalize();
  5755. }
  5756. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5757. if (!this._raw) {
  5758. this._binormals[i].normalize();
  5759. }
  5760. }
  5761. };
  5762. // private function getFirstNonNullVector(index)
  5763. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5764. Path3D.prototype._getFirstNonNullVector = function (index) {
  5765. var i = 1;
  5766. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5767. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5768. i++;
  5769. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5770. }
  5771. return nNVector;
  5772. };
  5773. // private function getLastNonNullVector(index)
  5774. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5775. Path3D.prototype._getLastNonNullVector = function (index) {
  5776. var i = 1;
  5777. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5778. while (nLVector.length() === 0 && index > i + 1) {
  5779. i++;
  5780. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5781. }
  5782. return nLVector;
  5783. };
  5784. // private function normalVector(v0, vt, va) :
  5785. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5786. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5787. Path3D.prototype._normalVector = function (v0, vt, va) {
  5788. var normal0;
  5789. var tgl = vt.length();
  5790. if (tgl === 0.0) {
  5791. tgl = 1.0;
  5792. }
  5793. if (va === undefined || va === null) {
  5794. var point;
  5795. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5796. point = new Vector3(0.0, -1.0, 0.0);
  5797. }
  5798. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5799. point = new Vector3(1.0, 0.0, 0.0);
  5800. }
  5801. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5802. point = new Vector3(0.0, 0.0, 1.0);
  5803. }
  5804. else {
  5805. point = Vector3.Zero();
  5806. }
  5807. normal0 = Vector3.Cross(vt, point);
  5808. }
  5809. else {
  5810. normal0 = Vector3.Cross(vt, va);
  5811. Vector3.CrossToRef(normal0, vt, normal0);
  5812. }
  5813. normal0.normalize();
  5814. return normal0;
  5815. };
  5816. return Path3D;
  5817. }());
  5818. BABYLON.Path3D = Path3D;
  5819. var Curve3 = /** @class */ (function () {
  5820. /**
  5821. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5822. * A Curve3 is designed from a series of successive Vector3.
  5823. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5824. */
  5825. function Curve3(points) {
  5826. this._length = 0.0;
  5827. this._points = points;
  5828. this._length = this._computeLength(points);
  5829. }
  5830. /**
  5831. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5832. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5833. * @param v1 (Vector3) the control point
  5834. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5835. * @param nbPoints (integer) the wanted number of points in the curve
  5836. */
  5837. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5838. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5839. var bez = new Array();
  5840. var equation = function (t, val0, val1, val2) {
  5841. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5842. return res;
  5843. };
  5844. for (var i = 0; i <= nbPoints; i++) {
  5845. 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)));
  5846. }
  5847. return new Curve3(bez);
  5848. };
  5849. /**
  5850. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5851. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5852. * @param v1 (Vector3) the first control point
  5853. * @param v2 (Vector3) the second control point
  5854. * @param v3 (Vector3) the end point of the Cubic Bezier
  5855. * @param nbPoints (integer) the wanted number of points in the curve
  5856. */
  5857. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5858. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5859. var bez = new Array();
  5860. var equation = function (t, val0, val1, val2, val3) {
  5861. 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;
  5862. return res;
  5863. };
  5864. for (var i = 0; i <= nbPoints; i++) {
  5865. 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)));
  5866. }
  5867. return new Curve3(bez);
  5868. };
  5869. /**
  5870. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5871. * @param p1 (Vector3) the origin point of the Hermite Spline
  5872. * @param t1 (Vector3) the tangent vector at the origin point
  5873. * @param p2 (Vector3) the end point of the Hermite Spline
  5874. * @param t2 (Vector3) the tangent vector at the end point
  5875. * @param nbPoints (integer) the wanted number of points in the curve
  5876. */
  5877. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5878. var hermite = new Array();
  5879. var step = 1.0 / nbPoints;
  5880. for (var i = 0; i <= nbPoints; i++) {
  5881. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5882. }
  5883. return new Curve3(hermite);
  5884. };
  5885. /**
  5886. * Returns a Curve3 object along a CatmullRom Spline curve :
  5887. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5888. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5889. */
  5890. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5891. var totalPoints = new Array();
  5892. totalPoints.push(points[0].clone());
  5893. Array.prototype.push.apply(totalPoints, points);
  5894. totalPoints.push(points[points.length - 1].clone());
  5895. var catmullRom = new Array();
  5896. var step = 1.0 / nbPoints;
  5897. var amount = 0.0;
  5898. for (var i = 0; i < totalPoints.length - 3; i++) {
  5899. amount = 0;
  5900. for (var c = 0; c < nbPoints; c++) {
  5901. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5902. amount += step;
  5903. }
  5904. }
  5905. i--;
  5906. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5907. return new Curve3(catmullRom);
  5908. };
  5909. /**
  5910. * Returns the Curve3 stored array of successive Vector3
  5911. */
  5912. Curve3.prototype.getPoints = function () {
  5913. return this._points;
  5914. };
  5915. /**
  5916. * Returns the computed length (float) of the curve.
  5917. */
  5918. Curve3.prototype.length = function () {
  5919. return this._length;
  5920. };
  5921. /**
  5922. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5923. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5924. * curveA and curveB keep unchanged.
  5925. */
  5926. Curve3.prototype.continue = function (curve) {
  5927. var lastPoint = this._points[this._points.length - 1];
  5928. var continuedPoints = this._points.slice();
  5929. var curvePoints = curve.getPoints();
  5930. for (var i = 1; i < curvePoints.length; i++) {
  5931. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5932. }
  5933. var continuedCurve = new Curve3(continuedPoints);
  5934. return continuedCurve;
  5935. };
  5936. Curve3.prototype._computeLength = function (path) {
  5937. var l = 0;
  5938. for (var i = 1; i < path.length; i++) {
  5939. l += (path[i].subtract(path[i - 1])).length();
  5940. }
  5941. return l;
  5942. };
  5943. return Curve3;
  5944. }());
  5945. BABYLON.Curve3 = Curve3;
  5946. // Vertex formats
  5947. var PositionNormalVertex = /** @class */ (function () {
  5948. function PositionNormalVertex(position, normal) {
  5949. if (position === void 0) { position = Vector3.Zero(); }
  5950. if (normal === void 0) { normal = Vector3.Up(); }
  5951. this.position = position;
  5952. this.normal = normal;
  5953. }
  5954. PositionNormalVertex.prototype.clone = function () {
  5955. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5956. };
  5957. return PositionNormalVertex;
  5958. }());
  5959. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5960. var PositionNormalTextureVertex = /** @class */ (function () {
  5961. function PositionNormalTextureVertex(position, normal, uv) {
  5962. if (position === void 0) { position = Vector3.Zero(); }
  5963. if (normal === void 0) { normal = Vector3.Up(); }
  5964. if (uv === void 0) { uv = Vector2.Zero(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. this.uv = uv;
  5968. }
  5969. PositionNormalTextureVertex.prototype.clone = function () {
  5970. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5971. };
  5972. return PositionNormalTextureVertex;
  5973. }());
  5974. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5975. // Temporary pre-allocated objects for engine internal use
  5976. // usage in any internal function :
  5977. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5978. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5979. var Tmp = /** @class */ (function () {
  5980. function Tmp() {
  5981. }
  5982. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5983. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5984. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5985. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5986. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5987. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5988. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5989. Matrix.Zero(), Matrix.Zero(),
  5990. Matrix.Zero(), Matrix.Zero(),
  5991. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5992. return Tmp;
  5993. }());
  5994. BABYLON.Tmp = Tmp;
  5995. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5996. var MathTmp = /** @class */ (function () {
  5997. function MathTmp() {
  5998. }
  5999. MathTmp.Vector3 = [Vector3.Zero()];
  6000. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6001. MathTmp.Quaternion = [Quaternion.Zero()];
  6002. return MathTmp;
  6003. }());
  6004. })(BABYLON || (BABYLON = {}));
  6005. //# sourceMappingURL=babylon.math.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var Scalar = /** @class */ (function () {
  6009. function Scalar() {
  6010. }
  6011. /**
  6012. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6013. */
  6014. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6015. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6016. var num = a - b;
  6017. return -epsilon <= num && num <= epsilon;
  6018. };
  6019. /**
  6020. * Returns a string : the upper case translation of the number i to hexadecimal.
  6021. */
  6022. Scalar.ToHex = function (i) {
  6023. var str = i.toString(16);
  6024. if (i <= 15) {
  6025. return ("0" + str).toUpperCase();
  6026. }
  6027. return str.toUpperCase();
  6028. };
  6029. /**
  6030. * Returns -1 if value is negative and +1 is value is positive.
  6031. * Returns the value itself if it's equal to zero.
  6032. */
  6033. Scalar.Sign = function (value) {
  6034. value = +value; // convert to a number
  6035. if (value === 0 || isNaN(value))
  6036. return value;
  6037. return value > 0 ? 1 : -1;
  6038. };
  6039. /**
  6040. * Returns the value itself if it's between min and max.
  6041. * Returns min if the value is lower than min.
  6042. * Returns max if the value is greater than max.
  6043. */
  6044. Scalar.Clamp = function (value, min, max) {
  6045. if (min === void 0) { min = 0; }
  6046. if (max === void 0) { max = 1; }
  6047. return Math.min(max, Math.max(min, value));
  6048. };
  6049. /**
  6050. * Returns the log2 of value.
  6051. */
  6052. Scalar.Log2 = function (value) {
  6053. return Math.log(value) * Math.LOG2E;
  6054. };
  6055. /**
  6056. * Loops the value, so that it is never larger than length and never smaller than 0.
  6057. *
  6058. * This is similar to the modulo operator but it works with floating point numbers.
  6059. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6060. * With t = 5 and length = 2.5, the result would be 0.0.
  6061. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6062. */
  6063. Scalar.Repeat = function (value, length) {
  6064. return value - Math.floor(value / length) * length;
  6065. };
  6066. /**
  6067. * Normalize the value between 0.0 and 1.0 using min and max values
  6068. */
  6069. Scalar.Normalize = function (value, min, max) {
  6070. return (value - min) / (max - min);
  6071. };
  6072. /**
  6073. * Denormalize the value from 0.0 and 1.0 using min and max values
  6074. */
  6075. Scalar.Denormalize = function (normalized, min, max) {
  6076. return (normalized * (max - min) + min);
  6077. };
  6078. /**
  6079. * Calculates the shortest difference between two given angles given in degrees.
  6080. */
  6081. Scalar.DeltaAngle = function (current, target) {
  6082. var num = Scalar.Repeat(target - current, 360.0);
  6083. if (num > 180.0) {
  6084. num -= 360.0;
  6085. }
  6086. return num;
  6087. };
  6088. /**
  6089. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6090. *
  6091. * The returned value will move back and forth between 0 and length
  6092. */
  6093. Scalar.PingPong = function (tx, length) {
  6094. var t = Scalar.Repeat(tx, length * 2.0);
  6095. return length - Math.abs(t - length);
  6096. };
  6097. /**
  6098. * Interpolates between min and max with smoothing at the limits.
  6099. *
  6100. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6101. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6102. */
  6103. Scalar.SmoothStep = function (from, to, tx) {
  6104. var t = Scalar.Clamp(tx);
  6105. t = -2.0 * t * t * t + 3.0 * t * t;
  6106. return to * t + from * (1.0 - t);
  6107. };
  6108. /**
  6109. * Moves a value current towards target.
  6110. *
  6111. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6112. * Negative values of maxDelta pushes the value away from target.
  6113. */
  6114. Scalar.MoveTowards = function (current, target, maxDelta) {
  6115. var result = 0;
  6116. if (Math.abs(target - current) <= maxDelta) {
  6117. result = target;
  6118. }
  6119. else {
  6120. result = current + Scalar.Sign(target - current) * maxDelta;
  6121. }
  6122. return result;
  6123. };
  6124. /**
  6125. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6126. *
  6127. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6128. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6129. */
  6130. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6131. var num = Scalar.DeltaAngle(current, target);
  6132. var result = 0;
  6133. if (-maxDelta < num && num < maxDelta) {
  6134. result = target;
  6135. }
  6136. else {
  6137. target = current + num;
  6138. result = Scalar.MoveTowards(current, target, maxDelta);
  6139. }
  6140. return result;
  6141. };
  6142. /**
  6143. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6144. */
  6145. Scalar.Lerp = function (start, end, amount) {
  6146. return start + ((end - start) * amount);
  6147. };
  6148. /**
  6149. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6150. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6151. */
  6152. Scalar.LerpAngle = function (start, end, amount) {
  6153. var num = Scalar.Repeat(end - start, 360.0);
  6154. if (num > 180.0) {
  6155. num -= 360.0;
  6156. }
  6157. return start + num * Scalar.Clamp(amount);
  6158. };
  6159. /**
  6160. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6161. */
  6162. Scalar.InverseLerp = function (a, b, value) {
  6163. var result = 0;
  6164. if (a != b) {
  6165. result = Scalar.Clamp((value - a) / (b - a));
  6166. }
  6167. else {
  6168. result = 0.0;
  6169. }
  6170. return result;
  6171. };
  6172. /**
  6173. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6174. */
  6175. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6176. var squared = amount * amount;
  6177. var cubed = amount * squared;
  6178. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6179. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6180. var part3 = (cubed - (2.0 * squared)) + amount;
  6181. var part4 = cubed - squared;
  6182. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6183. };
  6184. /**
  6185. * Returns a random float number between and min and max values
  6186. */
  6187. Scalar.RandomRange = function (min, max) {
  6188. if (min === max)
  6189. return min;
  6190. return ((Math.random() * (max - min)) + min);
  6191. };
  6192. /**
  6193. * This function returns percentage of a number in a given range.
  6194. *
  6195. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6196. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6197. */
  6198. Scalar.RangeToPercent = function (number, min, max) {
  6199. return ((number - min) / (max - min));
  6200. };
  6201. /**
  6202. * This function returns number that corresponds to the percentage in a given range.
  6203. *
  6204. * PercentToRange(0.34,0,100) will return 34.
  6205. */
  6206. Scalar.PercentToRange = function (percent, min, max) {
  6207. return ((max - min) * percent + min);
  6208. };
  6209. /**
  6210. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6211. * @param angle The angle to normalize in radian.
  6212. * @return The converted angle.
  6213. */
  6214. Scalar.NormalizeRadians = function (angle) {
  6215. // More precise but slower version kept for reference.
  6216. // angle = angle % Tools.TwoPi;
  6217. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6218. //if (angle > Math.PI) {
  6219. // angle -= Tools.TwoPi;
  6220. //}
  6221. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6222. return angle;
  6223. };
  6224. /**
  6225. * Two pi constants convenient for computation.
  6226. */
  6227. Scalar.TwoPi = Math.PI * 2;
  6228. return Scalar;
  6229. }());
  6230. BABYLON.Scalar = Scalar;
  6231. })(BABYLON || (BABYLON = {}));
  6232. //# sourceMappingURL=babylon.math.scalar.js.map
  6233. //# sourceMappingURL=babylon.mixins.js.map
  6234. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6235. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6236. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6237. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6238. //# sourceMappingURL=babylon.webgl2.js.map
  6239. var BABYLON;
  6240. (function (BABYLON) {
  6241. var __decoratorInitialStore = {};
  6242. var __mergedStore = {};
  6243. var _copySource = function (creationFunction, source, instanciate) {
  6244. var destination = creationFunction();
  6245. // Tags
  6246. if (BABYLON.Tags) {
  6247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6248. }
  6249. var classStore = getMergedStore(destination);
  6250. // Properties
  6251. for (var property in classStore) {
  6252. var propertyDescriptor = classStore[property];
  6253. var sourceProperty = source[property];
  6254. var propertyType = propertyDescriptor.type;
  6255. if (sourceProperty !== undefined && sourceProperty !== null) {
  6256. switch (propertyType) {
  6257. case 0: // Value
  6258. case 6:// Mesh reference
  6259. destination[property] = sourceProperty;
  6260. break;
  6261. case 1:// Texture
  6262. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6263. break;
  6264. case 2: // Color3
  6265. case 3: // FresnelParameters
  6266. case 4: // Vector2
  6267. case 5: // Vector3
  6268. case 7: // Color Curves
  6269. case 10:// Quaternion
  6270. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6271. break;
  6272. }
  6273. }
  6274. }
  6275. return destination;
  6276. };
  6277. function getDirectStore(target) {
  6278. var classKey = target.getClassName();
  6279. if (!__decoratorInitialStore[classKey]) {
  6280. __decoratorInitialStore[classKey] = {};
  6281. }
  6282. return __decoratorInitialStore[classKey];
  6283. }
  6284. /**
  6285. * Return the list of properties flagged as serializable
  6286. * @param target: host object
  6287. */
  6288. function getMergedStore(target) {
  6289. var classKey = target.getClassName();
  6290. if (__mergedStore[classKey]) {
  6291. return __mergedStore[classKey];
  6292. }
  6293. __mergedStore[classKey] = {};
  6294. var store = __mergedStore[classKey];
  6295. var currentTarget = target;
  6296. var currentKey = classKey;
  6297. while (currentKey) {
  6298. var initialStore = __decoratorInitialStore[currentKey];
  6299. for (var property in initialStore) {
  6300. store[property] = initialStore[property];
  6301. }
  6302. var parent_1 = void 0;
  6303. var done = false;
  6304. do {
  6305. parent_1 = Object.getPrototypeOf(currentTarget);
  6306. if (!parent_1.getClassName) {
  6307. done = true;
  6308. break;
  6309. }
  6310. if (parent_1.getClassName() !== currentKey) {
  6311. break;
  6312. }
  6313. currentTarget = parent_1;
  6314. } while (parent_1);
  6315. if (done) {
  6316. break;
  6317. }
  6318. currentKey = parent_1.getClassName();
  6319. currentTarget = parent_1;
  6320. }
  6321. return store;
  6322. }
  6323. function generateSerializableMember(type, sourceName) {
  6324. return function (target, propertyKey) {
  6325. var classStore = getDirectStore(target);
  6326. if (!classStore[propertyKey]) {
  6327. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6328. }
  6329. };
  6330. }
  6331. function generateExpandMember(setCallback, targetKey) {
  6332. if (targetKey === void 0) { targetKey = null; }
  6333. return function (target, propertyKey) {
  6334. var key = targetKey || ("_" + propertyKey);
  6335. Object.defineProperty(target, propertyKey, {
  6336. get: function () {
  6337. return this[key];
  6338. },
  6339. set: function (value) {
  6340. if (this[key] === value) {
  6341. return;
  6342. }
  6343. this[key] = value;
  6344. target[setCallback].apply(this);
  6345. },
  6346. enumerable: true,
  6347. configurable: true
  6348. });
  6349. };
  6350. }
  6351. function expandToProperty(callback, targetKey) {
  6352. if (targetKey === void 0) { targetKey = null; }
  6353. return generateExpandMember(callback, targetKey);
  6354. }
  6355. BABYLON.expandToProperty = expandToProperty;
  6356. function serialize(sourceName) {
  6357. return generateSerializableMember(0, sourceName); // value member
  6358. }
  6359. BABYLON.serialize = serialize;
  6360. function serializeAsTexture(sourceName) {
  6361. return generateSerializableMember(1, sourceName); // texture member
  6362. }
  6363. BABYLON.serializeAsTexture = serializeAsTexture;
  6364. function serializeAsColor3(sourceName) {
  6365. return generateSerializableMember(2, sourceName); // color3 member
  6366. }
  6367. BABYLON.serializeAsColor3 = serializeAsColor3;
  6368. function serializeAsFresnelParameters(sourceName) {
  6369. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6370. }
  6371. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6372. function serializeAsVector2(sourceName) {
  6373. return generateSerializableMember(4, sourceName); // vector2 member
  6374. }
  6375. BABYLON.serializeAsVector2 = serializeAsVector2;
  6376. function serializeAsVector3(sourceName) {
  6377. return generateSerializableMember(5, sourceName); // vector3 member
  6378. }
  6379. BABYLON.serializeAsVector3 = serializeAsVector3;
  6380. function serializeAsMeshReference(sourceName) {
  6381. return generateSerializableMember(6, sourceName); // mesh reference member
  6382. }
  6383. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6384. function serializeAsColorCurves(sourceName) {
  6385. return generateSerializableMember(7, sourceName); // color curves
  6386. }
  6387. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6388. function serializeAsColor4(sourceName) {
  6389. return generateSerializableMember(8, sourceName); // color 4
  6390. }
  6391. BABYLON.serializeAsColor4 = serializeAsColor4;
  6392. function serializeAsImageProcessingConfiguration(sourceName) {
  6393. return generateSerializableMember(9, sourceName); // image processing
  6394. }
  6395. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6396. function serializeAsQuaternion(sourceName) {
  6397. return generateSerializableMember(10, sourceName); // quaternion member
  6398. }
  6399. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6400. var SerializationHelper = /** @class */ (function () {
  6401. function SerializationHelper() {
  6402. }
  6403. SerializationHelper.Serialize = function (entity, serializationObject) {
  6404. if (!serializationObject) {
  6405. serializationObject = {};
  6406. }
  6407. // Tags
  6408. if (BABYLON.Tags) {
  6409. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6410. }
  6411. var serializedProperties = getMergedStore(entity);
  6412. // Properties
  6413. for (var property in serializedProperties) {
  6414. var propertyDescriptor = serializedProperties[property];
  6415. var targetPropertyName = propertyDescriptor.sourceName || property;
  6416. var propertyType = propertyDescriptor.type;
  6417. var sourceProperty = entity[property];
  6418. if (sourceProperty !== undefined && sourceProperty !== null) {
  6419. switch (propertyType) {
  6420. case 0:// Value
  6421. serializationObject[targetPropertyName] = sourceProperty;
  6422. break;
  6423. case 1:// Texture
  6424. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6425. break;
  6426. case 2:// Color3
  6427. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6428. break;
  6429. case 3:// FresnelParameters
  6430. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6431. break;
  6432. case 4:// Vector2
  6433. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6434. break;
  6435. case 5:// Vector3
  6436. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6437. break;
  6438. case 6:// Mesh reference
  6439. serializationObject[targetPropertyName] = sourceProperty.id;
  6440. break;
  6441. case 7:// Color Curves
  6442. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6443. break;
  6444. case 8:// Color 4
  6445. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6446. break;
  6447. case 9:// Image Processing
  6448. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. return serializationObject;
  6454. };
  6455. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6456. if (rootUrl === void 0) { rootUrl = null; }
  6457. var destination = creationFunction();
  6458. if (!rootUrl) {
  6459. rootUrl = "";
  6460. }
  6461. // Tags
  6462. if (BABYLON.Tags) {
  6463. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6464. }
  6465. var classStore = getMergedStore(destination);
  6466. // Properties
  6467. for (var property in classStore) {
  6468. var propertyDescriptor = classStore[property];
  6469. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6470. var propertyType = propertyDescriptor.type;
  6471. if (sourceProperty !== undefined && sourceProperty !== null) {
  6472. var dest = destination;
  6473. switch (propertyType) {
  6474. case 0:// Value
  6475. dest[property] = sourceProperty;
  6476. break;
  6477. case 1:// Texture
  6478. if (scene) {
  6479. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6480. }
  6481. break;
  6482. case 2:// Color3
  6483. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6484. break;
  6485. case 3:// FresnelParameters
  6486. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6487. break;
  6488. case 4:// Vector2
  6489. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6490. break;
  6491. case 5:// Vector3
  6492. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6493. break;
  6494. case 6:// Mesh reference
  6495. if (scene) {
  6496. dest[property] = scene.getLastMeshByID(sourceProperty);
  6497. }
  6498. break;
  6499. case 7:// Color Curves
  6500. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6501. break;
  6502. case 8:// Color 4
  6503. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6504. break;
  6505. case 9:// Image Processing
  6506. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6507. break;
  6508. }
  6509. }
  6510. }
  6511. return destination;
  6512. };
  6513. SerializationHelper.Clone = function (creationFunction, source) {
  6514. return _copySource(creationFunction, source, false);
  6515. };
  6516. SerializationHelper.Instanciate = function (creationFunction, source) {
  6517. return _copySource(creationFunction, source, true);
  6518. };
  6519. return SerializationHelper;
  6520. }());
  6521. BABYLON.SerializationHelper = SerializationHelper;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.decorators.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. /**
  6527. * A class serves as a medium between the observable and its observers
  6528. */
  6529. var EventState = /** @class */ (function () {
  6530. /**
  6531. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6532. */
  6533. function EventState(mask, skipNextObservers, target, currentTarget) {
  6534. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6535. this.initalize(mask, skipNextObservers, target, currentTarget);
  6536. }
  6537. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6538. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6539. this.mask = mask;
  6540. this.skipNextObservers = skipNextObservers;
  6541. this.target = target;
  6542. this.currentTarget = currentTarget;
  6543. return this;
  6544. };
  6545. return EventState;
  6546. }());
  6547. BABYLON.EventState = EventState;
  6548. /**
  6549. * Represent an Observer registered to a given Observable object.
  6550. */
  6551. var Observer = /** @class */ (function () {
  6552. function Observer(callback, mask, scope) {
  6553. if (scope === void 0) { scope = null; }
  6554. this.callback = callback;
  6555. this.mask = mask;
  6556. this.scope = scope;
  6557. }
  6558. return Observer;
  6559. }());
  6560. BABYLON.Observer = Observer;
  6561. /**
  6562. * Represent a list of observers registered to multiple Observables object.
  6563. */
  6564. var MultiObserver = /** @class */ (function () {
  6565. function MultiObserver() {
  6566. }
  6567. MultiObserver.prototype.dispose = function () {
  6568. if (this._observers && this._observables) {
  6569. for (var index = 0; index < this._observers.length; index++) {
  6570. this._observables[index].remove(this._observers[index]);
  6571. }
  6572. }
  6573. this._observers = null;
  6574. this._observables = null;
  6575. };
  6576. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6577. if (mask === void 0) { mask = -1; }
  6578. if (scope === void 0) { scope = null; }
  6579. var result = new MultiObserver();
  6580. result._observers = new Array();
  6581. result._observables = observables;
  6582. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6583. var observable = observables_1[_i];
  6584. var observer = observable.add(callback, mask, false, scope);
  6585. if (observer) {
  6586. result._observers.push(observer);
  6587. }
  6588. }
  6589. return result;
  6590. };
  6591. return MultiObserver;
  6592. }());
  6593. BABYLON.MultiObserver = MultiObserver;
  6594. /**
  6595. * The Observable class is a simple implementation of the Observable pattern.
  6596. * 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.
  6597. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6598. * 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).
  6599. * 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.
  6600. */
  6601. var Observable = /** @class */ (function () {
  6602. function Observable(onObserverAdded) {
  6603. this._observers = new Array();
  6604. this._eventState = new EventState(0);
  6605. if (onObserverAdded) {
  6606. this._onObserverAdded = onObserverAdded;
  6607. }
  6608. }
  6609. /**
  6610. * Create a new Observer with the specified callback
  6611. * @param callback the callback that will be executed for that Observer
  6612. * @param mask the mask used to filter observers
  6613. * @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.
  6614. * @param scope optional scope for the callback to be called from
  6615. */
  6616. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6617. if (mask === void 0) { mask = -1; }
  6618. if (insertFirst === void 0) { insertFirst = false; }
  6619. if (scope === void 0) { scope = null; }
  6620. if (!callback) {
  6621. return null;
  6622. }
  6623. var observer = new Observer(callback, mask, scope);
  6624. if (insertFirst) {
  6625. this._observers.unshift(observer);
  6626. }
  6627. else {
  6628. this._observers.push(observer);
  6629. }
  6630. if (this._onObserverAdded) {
  6631. this._onObserverAdded(observer);
  6632. }
  6633. return observer;
  6634. };
  6635. /**
  6636. * Remove an Observer from the Observable object
  6637. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6638. */
  6639. Observable.prototype.remove = function (observer) {
  6640. if (!observer) {
  6641. return false;
  6642. }
  6643. var index = this._observers.indexOf(observer);
  6644. if (index !== -1) {
  6645. this._observers.splice(index, 1);
  6646. return true;
  6647. }
  6648. return false;
  6649. };
  6650. /**
  6651. * Remove a callback from the Observable object
  6652. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6653. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6654. */
  6655. Observable.prototype.removeCallback = function (callback, scope) {
  6656. for (var index = 0; index < this._observers.length; index++) {
  6657. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6658. this._observers.splice(index, 1);
  6659. return true;
  6660. }
  6661. }
  6662. return false;
  6663. };
  6664. /**
  6665. * Notify all Observers by calling their respective callback with the given data
  6666. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6667. * @param eventData
  6668. * @param mask
  6669. */
  6670. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6671. if (mask === void 0) { mask = -1; }
  6672. if (!this._observers.length) {
  6673. return true;
  6674. }
  6675. var state = this._eventState;
  6676. state.mask = mask;
  6677. state.target = target;
  6678. state.currentTarget = currentTarget;
  6679. state.skipNextObservers = false;
  6680. state.lastReturnValue = eventData;
  6681. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6682. var obs = _a[_i];
  6683. if (obs.mask & mask) {
  6684. if (obs.scope) {
  6685. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6686. }
  6687. else {
  6688. state.lastReturnValue = obs.callback(eventData, state);
  6689. }
  6690. }
  6691. if (state.skipNextObservers) {
  6692. return false;
  6693. }
  6694. }
  6695. return true;
  6696. };
  6697. /**
  6698. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6699. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6700. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6701. * and it is crucial that all callbacks will be executed.
  6702. * The order of the callbacks is kept, callbacks are not executed parallel.
  6703. *
  6704. * @param eventData The data to be sent to each callback
  6705. * @param mask is used to filter observers defaults to -1
  6706. * @param target the callback target (see EventState)
  6707. * @param currentTarget The current object in the bubbling phase
  6708. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6709. */
  6710. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6711. if (mask === void 0) { mask = -1; }
  6712. // create an empty promise
  6713. var p = Promise.resolve(eventData);
  6714. // no observers? return this promise.
  6715. if (!this._observers.length) {
  6716. return p;
  6717. }
  6718. var state = this._eventState;
  6719. state.mask = mask;
  6720. state.target = target;
  6721. state.currentTarget = currentTarget;
  6722. state.skipNextObservers = false;
  6723. // execute one callback after another (not using Promise.all, the order is important)
  6724. this._observers.forEach(function (obs) {
  6725. if (state.skipNextObservers) {
  6726. return;
  6727. }
  6728. if (obs.mask & mask) {
  6729. if (obs.scope) {
  6730. p = p.then(function (lastReturnedValue) {
  6731. state.lastReturnValue = lastReturnedValue;
  6732. return obs.callback.apply(obs.scope, [eventData, state]);
  6733. });
  6734. }
  6735. else {
  6736. p = p.then(function (lastReturnedValue) {
  6737. state.lastReturnValue = lastReturnedValue;
  6738. return obs.callback(eventData, state);
  6739. });
  6740. }
  6741. }
  6742. });
  6743. // return the eventData
  6744. return p.then(function () { return eventData; });
  6745. };
  6746. /**
  6747. * Notify a specific observer
  6748. * @param eventData
  6749. * @param mask
  6750. */
  6751. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6752. if (mask === void 0) { mask = -1; }
  6753. var state = this._eventState;
  6754. state.mask = mask;
  6755. state.skipNextObservers = false;
  6756. observer.callback(eventData, state);
  6757. };
  6758. /**
  6759. * return true is the Observable has at least one Observer registered
  6760. */
  6761. Observable.prototype.hasObservers = function () {
  6762. return this._observers.length > 0;
  6763. };
  6764. /**
  6765. * Clear the list of observers
  6766. */
  6767. Observable.prototype.clear = function () {
  6768. this._observers = new Array();
  6769. this._onObserverAdded = null;
  6770. };
  6771. /**
  6772. * Clone the current observable
  6773. */
  6774. Observable.prototype.clone = function () {
  6775. var result = new Observable();
  6776. result._observers = this._observers.slice(0);
  6777. return result;
  6778. };
  6779. /**
  6780. * Does this observable handles observer registered with a given mask
  6781. * @param {number} trigger - the mask to be tested
  6782. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6783. **/
  6784. Observable.prototype.hasSpecificMask = function (mask) {
  6785. if (mask === void 0) { mask = -1; }
  6786. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6787. var obs = _a[_i];
  6788. if (obs.mask & mask || obs.mask === mask) {
  6789. return true;
  6790. }
  6791. }
  6792. return false;
  6793. };
  6794. return Observable;
  6795. }());
  6796. BABYLON.Observable = Observable;
  6797. })(BABYLON || (BABYLON = {}));
  6798. //# sourceMappingURL=babylon.observable.js.map
  6799. var BABYLON;
  6800. (function (BABYLON) {
  6801. var SmartArray = /** @class */ (function () {
  6802. function SmartArray(capacity) {
  6803. this.length = 0;
  6804. this.data = new Array(capacity);
  6805. this._id = SmartArray._GlobalId++;
  6806. }
  6807. SmartArray.prototype.push = function (value) {
  6808. this.data[this.length++] = value;
  6809. if (this.length > this.data.length) {
  6810. this.data.length *= 2;
  6811. }
  6812. };
  6813. SmartArray.prototype.forEach = function (func) {
  6814. for (var index = 0; index < this.length; index++) {
  6815. func(this.data[index]);
  6816. }
  6817. };
  6818. SmartArray.prototype.sort = function (compareFn) {
  6819. this.data.sort(compareFn);
  6820. };
  6821. SmartArray.prototype.reset = function () {
  6822. this.length = 0;
  6823. };
  6824. SmartArray.prototype.dispose = function () {
  6825. this.reset();
  6826. if (this.data) {
  6827. this.data.length = 0;
  6828. this.data = [];
  6829. }
  6830. };
  6831. SmartArray.prototype.concat = function (array) {
  6832. if (array.length === 0) {
  6833. return;
  6834. }
  6835. if (this.length + array.length > this.data.length) {
  6836. this.data.length = (this.length + array.length) * 2;
  6837. }
  6838. for (var index = 0; index < array.length; index++) {
  6839. this.data[this.length++] = (array.data || array)[index];
  6840. }
  6841. };
  6842. SmartArray.prototype.indexOf = function (value) {
  6843. var position = this.data.indexOf(value);
  6844. if (position >= this.length) {
  6845. return -1;
  6846. }
  6847. return position;
  6848. };
  6849. SmartArray.prototype.contains = function (value) {
  6850. return this.data.indexOf(value) !== -1;
  6851. };
  6852. // Statics
  6853. SmartArray._GlobalId = 0;
  6854. return SmartArray;
  6855. }());
  6856. BABYLON.SmartArray = SmartArray;
  6857. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6858. __extends(SmartArrayNoDuplicate, _super);
  6859. function SmartArrayNoDuplicate() {
  6860. var _this = _super !== null && _super.apply(this, arguments) || this;
  6861. _this._duplicateId = 0;
  6862. return _this;
  6863. }
  6864. SmartArrayNoDuplicate.prototype.push = function (value) {
  6865. _super.prototype.push.call(this, value);
  6866. if (!value.__smartArrayFlags) {
  6867. value.__smartArrayFlags = {};
  6868. }
  6869. value.__smartArrayFlags[this._id] = this._duplicateId;
  6870. };
  6871. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6872. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6873. return false;
  6874. }
  6875. this.push(value);
  6876. return true;
  6877. };
  6878. SmartArrayNoDuplicate.prototype.reset = function () {
  6879. _super.prototype.reset.call(this);
  6880. this._duplicateId++;
  6881. };
  6882. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6883. if (array.length === 0) {
  6884. return;
  6885. }
  6886. if (this.length + array.length > this.data.length) {
  6887. this.data.length = (this.length + array.length) * 2;
  6888. }
  6889. for (var index = 0; index < array.length; index++) {
  6890. var item = (array.data || array)[index];
  6891. this.pushNoDuplicate(item);
  6892. }
  6893. };
  6894. return SmartArrayNoDuplicate;
  6895. }(SmartArray));
  6896. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6897. })(BABYLON || (BABYLON = {}));
  6898. //# sourceMappingURL=babylon.smartArray.js.map
  6899. var BABYLON;
  6900. (function (BABYLON) {
  6901. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6902. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6903. var LoadFileError = /** @class */ (function (_super) {
  6904. __extends(LoadFileError, _super);
  6905. function LoadFileError(message, request) {
  6906. var _this = _super.call(this, message) || this;
  6907. _this.request = request;
  6908. _this.name = "LoadFileError";
  6909. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6910. return _this;
  6911. }
  6912. // Polyfill for Object.setPrototypeOf if necessary.
  6913. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6914. return LoadFileError;
  6915. }(Error));
  6916. BABYLON.LoadFileError = LoadFileError;
  6917. var RetryStrategy = /** @class */ (function () {
  6918. function RetryStrategy() {
  6919. }
  6920. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6921. if (maxRetries === void 0) { maxRetries = 3; }
  6922. if (baseInterval === void 0) { baseInterval = 500; }
  6923. return function (url, request, retryIndex) {
  6924. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6925. return -1;
  6926. }
  6927. return Math.pow(2, retryIndex) * baseInterval;
  6928. };
  6929. };
  6930. return RetryStrategy;
  6931. }());
  6932. BABYLON.RetryStrategy = RetryStrategy;
  6933. // Screenshots
  6934. var screenshotCanvas;
  6935. var cloneValue = function (source, destinationObject) {
  6936. if (!source)
  6937. return null;
  6938. if (source instanceof BABYLON.Mesh) {
  6939. return null;
  6940. }
  6941. if (source instanceof BABYLON.SubMesh) {
  6942. return source.clone(destinationObject);
  6943. }
  6944. else if (source.clone) {
  6945. return source.clone();
  6946. }
  6947. return null;
  6948. };
  6949. var Tools = /** @class */ (function () {
  6950. function Tools() {
  6951. }
  6952. /**
  6953. * Interpolates between a and b via alpha
  6954. * @param a The lower value (returned when alpha = 0)
  6955. * @param b The upper value (returned when alpha = 1)
  6956. * @param alpha The interpolation-factor
  6957. * @return The mixed value
  6958. */
  6959. Tools.Mix = function (a, b, alpha) {
  6960. return a * (1 - alpha) + b * alpha;
  6961. };
  6962. Tools.Instantiate = function (className) {
  6963. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6964. return Tools.RegisteredExternalClasses[className];
  6965. }
  6966. var arr = className.split(".");
  6967. var fn = (window || this);
  6968. for (var i = 0, len = arr.length; i < len; i++) {
  6969. fn = fn[arr[i]];
  6970. }
  6971. if (typeof fn !== "function") {
  6972. return null;
  6973. }
  6974. return fn;
  6975. };
  6976. /**
  6977. * Provides a slice function that will work even on IE
  6978. * @param data defines the array to slice
  6979. * @returns the new sliced array
  6980. */
  6981. Tools.Slice = function (data) {
  6982. if (data.slice) {
  6983. return data.slice();
  6984. }
  6985. return Array.prototype.slice.call(data);
  6986. };
  6987. Tools.SetImmediate = function (action) {
  6988. if (window.setImmediate) {
  6989. window.setImmediate(action);
  6990. }
  6991. else {
  6992. setTimeout(action, 1);
  6993. }
  6994. };
  6995. Tools.IsExponentOfTwo = function (value) {
  6996. var count = 1;
  6997. do {
  6998. count *= 2;
  6999. } while (count < value);
  7000. return count === value;
  7001. };
  7002. /**
  7003. * Find the next highest power of two.
  7004. * @param x Number to start search from.
  7005. * @return Next highest power of two.
  7006. */
  7007. Tools.CeilingPOT = function (x) {
  7008. x--;
  7009. x |= x >> 1;
  7010. x |= x >> 2;
  7011. x |= x >> 4;
  7012. x |= x >> 8;
  7013. x |= x >> 16;
  7014. x++;
  7015. return x;
  7016. };
  7017. /**
  7018. * Find the next lowest power of two.
  7019. * @param x Number to start search from.
  7020. * @return Next lowest power of two.
  7021. */
  7022. Tools.FloorPOT = function (x) {
  7023. x = x | (x >> 1);
  7024. x = x | (x >> 2);
  7025. x = x | (x >> 4);
  7026. x = x | (x >> 8);
  7027. x = x | (x >> 16);
  7028. return x - (x >> 1);
  7029. };
  7030. /**
  7031. * Find the nearest power of two.
  7032. * @param x Number to start search from.
  7033. * @return Next nearest power of two.
  7034. */
  7035. Tools.NearestPOT = function (x) {
  7036. var c = Tools.CeilingPOT(x);
  7037. var f = Tools.FloorPOT(x);
  7038. return (c - x) > (x - f) ? f : c;
  7039. };
  7040. Tools.GetExponentOfTwo = function (value, max, mode) {
  7041. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7042. var pot;
  7043. switch (mode) {
  7044. case BABYLON.Engine.SCALEMODE_FLOOR:
  7045. pot = Tools.FloorPOT(value);
  7046. break;
  7047. case BABYLON.Engine.SCALEMODE_NEAREST:
  7048. pot = Tools.NearestPOT(value);
  7049. break;
  7050. case BABYLON.Engine.SCALEMODE_CEILING:
  7051. default:
  7052. pot = Tools.CeilingPOT(value);
  7053. break;
  7054. }
  7055. return Math.min(pot, max);
  7056. };
  7057. Tools.GetFilename = function (path) {
  7058. var index = path.lastIndexOf("/");
  7059. if (index < 0)
  7060. return path;
  7061. return path.substring(index + 1);
  7062. };
  7063. Tools.GetFolderPath = function (uri) {
  7064. var index = uri.lastIndexOf("/");
  7065. if (index < 0)
  7066. return "";
  7067. return uri.substring(0, index + 1);
  7068. };
  7069. Tools.GetDOMTextContent = function (element) {
  7070. var result = "";
  7071. var child = element.firstChild;
  7072. while (child) {
  7073. if (child.nodeType === 3) {
  7074. result += child.textContent;
  7075. }
  7076. child = child.nextSibling;
  7077. }
  7078. return result;
  7079. };
  7080. Tools.ToDegrees = function (angle) {
  7081. return angle * 180 / Math.PI;
  7082. };
  7083. Tools.ToRadians = function (angle) {
  7084. return angle * Math.PI / 180;
  7085. };
  7086. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7087. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7088. var output = "";
  7089. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7090. var i = 0;
  7091. var bytes = new Uint8Array(buffer);
  7092. while (i < bytes.length) {
  7093. chr1 = bytes[i++];
  7094. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7095. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7096. enc1 = chr1 >> 2;
  7097. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7098. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7099. enc4 = chr3 & 63;
  7100. if (isNaN(chr2)) {
  7101. enc3 = enc4 = 64;
  7102. }
  7103. else if (isNaN(chr3)) {
  7104. enc4 = 64;
  7105. }
  7106. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7107. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7108. }
  7109. return "data:image/png;base64," + output;
  7110. };
  7111. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7112. if (bias === void 0) { bias = null; }
  7113. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7114. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7115. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7116. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7117. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7118. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7119. }
  7120. if (bias) {
  7121. minimum.x -= minimum.x * bias.x + bias.y;
  7122. minimum.y -= minimum.y * bias.x + bias.y;
  7123. minimum.z -= minimum.z * bias.x + bias.y;
  7124. maximum.x += maximum.x * bias.x + bias.y;
  7125. maximum.y += maximum.y * bias.x + bias.y;
  7126. maximum.z += maximum.z * bias.x + bias.y;
  7127. }
  7128. return {
  7129. minimum: minimum,
  7130. maximum: maximum
  7131. };
  7132. };
  7133. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7134. if (bias === void 0) { bias = null; }
  7135. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7136. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7137. if (!stride) {
  7138. stride = 3;
  7139. }
  7140. for (var index = start; index < start + count; index++) {
  7141. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7142. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7143. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7144. }
  7145. if (bias) {
  7146. minimum.x -= minimum.x * bias.x + bias.y;
  7147. minimum.y -= minimum.y * bias.x + bias.y;
  7148. minimum.z -= minimum.z * bias.x + bias.y;
  7149. maximum.x += maximum.x * bias.x + bias.y;
  7150. maximum.y += maximum.y * bias.x + bias.y;
  7151. maximum.z += maximum.z * bias.x + bias.y;
  7152. }
  7153. return {
  7154. minimum: minimum,
  7155. maximum: maximum
  7156. };
  7157. };
  7158. Tools.Vector2ArrayFeeder = function (array) {
  7159. return function (index) {
  7160. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7161. var length = isFloatArray ? array.length / 2 : array.length;
  7162. if (index >= length) {
  7163. return null;
  7164. }
  7165. if (isFloatArray) {
  7166. var fa = array;
  7167. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7168. }
  7169. var a = array;
  7170. return a[index];
  7171. };
  7172. };
  7173. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7174. if (bias === void 0) { bias = null; }
  7175. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7176. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7177. var i = 0;
  7178. var cur = feeder(i++);
  7179. while (cur) {
  7180. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7181. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7182. cur = feeder(i++);
  7183. }
  7184. if (bias) {
  7185. minimum.x -= minimum.x * bias.x + bias.y;
  7186. minimum.y -= minimum.y * bias.x + bias.y;
  7187. maximum.x += maximum.x * bias.x + bias.y;
  7188. maximum.y += maximum.y * bias.x + bias.y;
  7189. }
  7190. return {
  7191. minimum: minimum,
  7192. maximum: maximum
  7193. };
  7194. };
  7195. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7196. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7197. return null;
  7198. return Array.isArray(obj) ? obj : [obj];
  7199. };
  7200. // Misc.
  7201. Tools.GetPointerPrefix = function () {
  7202. var eventPrefix = "pointer";
  7203. // Check if pointer events are supported
  7204. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7205. eventPrefix = "mouse";
  7206. }
  7207. return eventPrefix;
  7208. };
  7209. /**
  7210. * @param func - the function to be called
  7211. * @param requester - the object that will request the next frame. Falls back to window.
  7212. */
  7213. Tools.QueueNewFrame = function (func, requester) {
  7214. if (!Tools.IsWindowObjectExist()) {
  7215. return setTimeout(func, 16);
  7216. }
  7217. if (!requester) {
  7218. requester = window;
  7219. }
  7220. if (requester.requestAnimationFrame) {
  7221. return requester.requestAnimationFrame(func);
  7222. }
  7223. else if (requester.msRequestAnimationFrame) {
  7224. return requester.msRequestAnimationFrame(func);
  7225. }
  7226. else if (requester.webkitRequestAnimationFrame) {
  7227. return requester.webkitRequestAnimationFrame(func);
  7228. }
  7229. else if (requester.mozRequestAnimationFrame) {
  7230. return requester.mozRequestAnimationFrame(func);
  7231. }
  7232. else if (requester.oRequestAnimationFrame) {
  7233. return requester.oRequestAnimationFrame(func);
  7234. }
  7235. else {
  7236. return window.setTimeout(func, 16);
  7237. }
  7238. };
  7239. Tools.RequestFullscreen = function (element) {
  7240. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7241. if (!requestFunction)
  7242. return;
  7243. requestFunction.call(element);
  7244. };
  7245. Tools.ExitFullscreen = function () {
  7246. if (document.exitFullscreen) {
  7247. document.exitFullscreen();
  7248. }
  7249. else if (document.mozCancelFullScreen) {
  7250. document.mozCancelFullScreen();
  7251. }
  7252. else if (document.webkitCancelFullScreen) {
  7253. document.webkitCancelFullScreen();
  7254. }
  7255. else if (document.msCancelFullScreen) {
  7256. document.msCancelFullScreen();
  7257. }
  7258. };
  7259. Tools.SetCorsBehavior = function (url, element) {
  7260. if (url && url.indexOf("data:") === 0) {
  7261. return;
  7262. }
  7263. if (Tools.CorsBehavior) {
  7264. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7265. element.crossOrigin = Tools.CorsBehavior;
  7266. }
  7267. else {
  7268. var result = Tools.CorsBehavior(url);
  7269. if (result) {
  7270. element.crossOrigin = result;
  7271. }
  7272. }
  7273. }
  7274. };
  7275. // External files
  7276. Tools.CleanUrl = function (url) {
  7277. url = url.replace(/#/mg, "%23");
  7278. return url;
  7279. };
  7280. Tools.LoadImage = function (url, onLoad, onError, database) {
  7281. if (url instanceof ArrayBuffer) {
  7282. url = Tools.EncodeArrayBufferTobase64(url);
  7283. }
  7284. url = Tools.CleanUrl(url);
  7285. url = Tools.PreprocessUrl(url);
  7286. var img = new Image();
  7287. Tools.SetCorsBehavior(url, img);
  7288. img.onload = function () {
  7289. onLoad(img);
  7290. };
  7291. img.onerror = function (err) {
  7292. Tools.Error("Error while trying to load image: " + url);
  7293. if (onError) {
  7294. onError("Error while trying to load image: " + url, err);
  7295. }
  7296. };
  7297. var noIndexedDB = function () {
  7298. img.src = url;
  7299. };
  7300. var loadFromIndexedDB = function () {
  7301. if (database) {
  7302. database.loadImageFromDB(url, img);
  7303. }
  7304. };
  7305. //ANY database to do!
  7306. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7307. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7308. }
  7309. else {
  7310. if (url.indexOf("file:") !== -1) {
  7311. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7312. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7313. try {
  7314. var blobURL;
  7315. try {
  7316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7317. }
  7318. catch (ex) {
  7319. // Chrome doesn't support oneTimeOnly parameter
  7320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7321. }
  7322. img.src = blobURL;
  7323. }
  7324. catch (e) {
  7325. img.src = "";
  7326. }
  7327. return img;
  7328. }
  7329. }
  7330. noIndexedDB();
  7331. }
  7332. return img;
  7333. };
  7334. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7335. url = Tools.CleanUrl(url);
  7336. url = Tools.PreprocessUrl(url);
  7337. // If file and file input are set
  7338. if (url.indexOf("file:") !== -1) {
  7339. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7340. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7341. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7342. }
  7343. }
  7344. var loadUrl = Tools.BaseUrl + url;
  7345. var aborted = false;
  7346. var fileRequest = {
  7347. onCompleteObservable: new BABYLON.Observable(),
  7348. abort: function () { return aborted = true; },
  7349. };
  7350. var requestFile = function () {
  7351. var request = new XMLHttpRequest();
  7352. var retryHandle = null;
  7353. fileRequest.abort = function () {
  7354. aborted = true;
  7355. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7356. request.abort();
  7357. }
  7358. if (retryHandle !== null) {
  7359. clearTimeout(retryHandle);
  7360. retryHandle = null;
  7361. }
  7362. };
  7363. var retryLoop = function (retryIndex) {
  7364. request.open('GET', loadUrl, true);
  7365. if (useArrayBuffer) {
  7366. request.responseType = "arraybuffer";
  7367. }
  7368. if (onProgress) {
  7369. request.addEventListener("progress", onProgress);
  7370. }
  7371. var onLoadEnd = function () {
  7372. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7373. };
  7374. request.addEventListener("loadend", onLoadEnd);
  7375. var onReadyStateChange = function () {
  7376. if (aborted) {
  7377. return;
  7378. }
  7379. // In case of undefined state in some browsers.
  7380. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7381. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7382. request.removeEventListener("readystatechange", onReadyStateChange);
  7383. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7384. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7385. return;
  7386. }
  7387. var retryStrategy = Tools.DefaultRetryStrategy;
  7388. if (retryStrategy) {
  7389. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7390. if (waitTime !== -1) {
  7391. // Prevent the request from completing for retry.
  7392. request.removeEventListener("loadend", onLoadEnd);
  7393. request = new XMLHttpRequest();
  7394. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7395. return;
  7396. }
  7397. }
  7398. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7399. if (onError) {
  7400. onError(request, e);
  7401. }
  7402. else {
  7403. throw e;
  7404. }
  7405. }
  7406. };
  7407. request.addEventListener("readystatechange", onReadyStateChange);
  7408. request.send();
  7409. };
  7410. retryLoop(0);
  7411. };
  7412. // Caching all files
  7413. if (database && database.enableSceneOffline) {
  7414. var noIndexedDB_1 = function () {
  7415. if (!aborted) {
  7416. requestFile();
  7417. }
  7418. };
  7419. var loadFromIndexedDB = function () {
  7420. // TODO: database needs to support aborting and should return a IFileRequest
  7421. if (aborted) {
  7422. return;
  7423. }
  7424. if (database) {
  7425. database.loadFileFromDB(url, function (data) {
  7426. if (!aborted) {
  7427. onSuccess(data);
  7428. }
  7429. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7430. }, onProgress ? function (event) {
  7431. if (!aborted) {
  7432. onProgress(event);
  7433. }
  7434. } : undefined, noIndexedDB_1, useArrayBuffer);
  7435. }
  7436. };
  7437. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7438. }
  7439. else {
  7440. requestFile();
  7441. }
  7442. return fileRequest;
  7443. };
  7444. /**
  7445. * Load a script (identified by an url). When the url returns, the
  7446. * content of this file is added into a new script element, attached to the DOM (body element)
  7447. */
  7448. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7449. var head = document.getElementsByTagName('head')[0];
  7450. var script = document.createElement('script');
  7451. script.type = 'text/javascript';
  7452. script.src = scriptUrl;
  7453. script.onload = function () {
  7454. if (onSuccess) {
  7455. onSuccess();
  7456. }
  7457. };
  7458. script.onerror = function (e) {
  7459. if (onError) {
  7460. onError("Unable to load script", e);
  7461. }
  7462. };
  7463. head.appendChild(script);
  7464. };
  7465. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7466. var reader = new FileReader();
  7467. var request = {
  7468. onCompleteObservable: new BABYLON.Observable(),
  7469. abort: function () { return reader.abort(); },
  7470. };
  7471. reader.onloadend = function (e) {
  7472. request.onCompleteObservable.notifyObservers(request);
  7473. };
  7474. reader.onload = function (e) {
  7475. //target doesn't have result from ts 1.3
  7476. callback(e.target['result']);
  7477. };
  7478. reader.onprogress = progressCallback;
  7479. reader.readAsDataURL(fileToLoad);
  7480. return request;
  7481. };
  7482. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7483. var reader = new FileReader();
  7484. var request = {
  7485. onCompleteObservable: new BABYLON.Observable(),
  7486. abort: function () { return reader.abort(); },
  7487. };
  7488. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7489. reader.onerror = function (e) {
  7490. Tools.Log("Error while reading file: " + fileToLoad.name);
  7491. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7492. };
  7493. reader.onload = function (e) {
  7494. //target doesn't have result from ts 1.3
  7495. callback(e.target['result']);
  7496. };
  7497. if (progressCallBack) {
  7498. reader.onprogress = progressCallBack;
  7499. }
  7500. if (!useArrayBuffer) {
  7501. // Asynchronous read
  7502. reader.readAsText(fileToLoad);
  7503. }
  7504. else {
  7505. reader.readAsArrayBuffer(fileToLoad);
  7506. }
  7507. return request;
  7508. };
  7509. //returns a downloadable url to a file content.
  7510. Tools.FileAsURL = function (content) {
  7511. var fileBlob = new Blob([content]);
  7512. var url = window.URL || window.webkitURL;
  7513. var link = url.createObjectURL(fileBlob);
  7514. return link;
  7515. };
  7516. // Misc.
  7517. Tools.Format = function (value, decimals) {
  7518. if (decimals === void 0) { decimals = 2; }
  7519. return value.toFixed(decimals);
  7520. };
  7521. Tools.CheckExtends = function (v, min, max) {
  7522. if (v.x < min.x)
  7523. min.x = v.x;
  7524. if (v.y < min.y)
  7525. min.y = v.y;
  7526. if (v.z < min.z)
  7527. min.z = v.z;
  7528. if (v.x > max.x)
  7529. max.x = v.x;
  7530. if (v.y > max.y)
  7531. max.y = v.y;
  7532. if (v.z > max.z)
  7533. max.z = v.z;
  7534. };
  7535. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7536. for (var prop in source) {
  7537. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7538. continue;
  7539. }
  7540. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7541. continue;
  7542. }
  7543. var sourceValue = source[prop];
  7544. var typeOfSourceValue = typeof sourceValue;
  7545. if (typeOfSourceValue === "function") {
  7546. continue;
  7547. }
  7548. if (typeOfSourceValue === "object") {
  7549. if (sourceValue instanceof Array) {
  7550. destination[prop] = [];
  7551. if (sourceValue.length > 0) {
  7552. if (typeof sourceValue[0] == "object") {
  7553. for (var index = 0; index < sourceValue.length; index++) {
  7554. var clonedValue = cloneValue(sourceValue[index], destination);
  7555. if (destination[prop].indexOf(clonedValue) === -1) {
  7556. destination[prop].push(clonedValue);
  7557. }
  7558. }
  7559. }
  7560. else {
  7561. destination[prop] = sourceValue.slice(0);
  7562. }
  7563. }
  7564. }
  7565. else {
  7566. destination[prop] = cloneValue(sourceValue, destination);
  7567. }
  7568. }
  7569. else {
  7570. destination[prop] = sourceValue;
  7571. }
  7572. }
  7573. };
  7574. Tools.IsEmpty = function (obj) {
  7575. for (var i in obj) {
  7576. if (obj.hasOwnProperty(i)) {
  7577. return false;
  7578. }
  7579. }
  7580. return true;
  7581. };
  7582. Tools.RegisterTopRootEvents = function (events) {
  7583. for (var index = 0; index < events.length; index++) {
  7584. var event = events[index];
  7585. window.addEventListener(event.name, event.handler, false);
  7586. try {
  7587. if (window.parent) {
  7588. window.parent.addEventListener(event.name, event.handler, false);
  7589. }
  7590. }
  7591. catch (e) {
  7592. // Silently fails...
  7593. }
  7594. }
  7595. };
  7596. Tools.UnregisterTopRootEvents = function (events) {
  7597. for (var index = 0; index < events.length; index++) {
  7598. var event = events[index];
  7599. window.removeEventListener(event.name, event.handler);
  7600. try {
  7601. if (window.parent) {
  7602. window.parent.removeEventListener(event.name, event.handler);
  7603. }
  7604. }
  7605. catch (e) {
  7606. // Silently fails...
  7607. }
  7608. }
  7609. };
  7610. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7611. if (mimeType === void 0) { mimeType = "image/png"; }
  7612. // Read the contents of the framebuffer
  7613. var numberOfChannelsByLine = width * 4;
  7614. var halfHeight = height / 2;
  7615. //Reading datas from WebGL
  7616. var data = engine.readPixels(0, 0, width, height);
  7617. //To flip image on Y axis.
  7618. for (var i = 0; i < halfHeight; i++) {
  7619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7620. var currentCell = j + i * numberOfChannelsByLine;
  7621. var targetLine = height - i - 1;
  7622. var targetCell = j + targetLine * numberOfChannelsByLine;
  7623. var temp = data[currentCell];
  7624. data[currentCell] = data[targetCell];
  7625. data[targetCell] = temp;
  7626. }
  7627. }
  7628. // Create a 2D canvas to store the result
  7629. if (!screenshotCanvas) {
  7630. screenshotCanvas = document.createElement('canvas');
  7631. }
  7632. screenshotCanvas.width = width;
  7633. screenshotCanvas.height = height;
  7634. var context = screenshotCanvas.getContext('2d');
  7635. if (context) {
  7636. // Copy the pixels to a 2D canvas
  7637. var imageData = context.createImageData(width, height);
  7638. var castData = (imageData.data);
  7639. castData.set(data);
  7640. context.putImageData(imageData, 0, 0);
  7641. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7642. }
  7643. };
  7644. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7645. if (mimeType === void 0) { mimeType = "image/png"; }
  7646. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7647. if (successCallback) {
  7648. successCallback(base64Image);
  7649. }
  7650. else {
  7651. // We need HTMLCanvasElement.toBlob for HD screenshots
  7652. if (!screenshotCanvas.toBlob) {
  7653. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7654. screenshotCanvas.toBlob = function (callback, type, quality) {
  7655. var _this = this;
  7656. setTimeout(function () {
  7657. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7658. for (var i = 0; i < len; i++) {
  7659. arr[i] = binStr.charCodeAt(i);
  7660. }
  7661. callback(new Blob([arr], { type: type || 'image/png' }));
  7662. });
  7663. };
  7664. }
  7665. screenshotCanvas.toBlob(function (blob) {
  7666. var url = URL.createObjectURL(blob);
  7667. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7668. if (("download" in document.createElement("a"))) {
  7669. var a = window.document.createElement("a");
  7670. a.href = url;
  7671. if (fileName) {
  7672. a.setAttribute("download", fileName);
  7673. }
  7674. else {
  7675. var date = new Date();
  7676. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7677. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7678. }
  7679. window.document.body.appendChild(a);
  7680. a.addEventListener("click", function () {
  7681. if (a.parentElement) {
  7682. a.parentElement.removeChild(a);
  7683. }
  7684. });
  7685. a.click();
  7686. }
  7687. else {
  7688. var newWindow = window.open("");
  7689. if (!newWindow)
  7690. return;
  7691. var img = newWindow.document.createElement("img");
  7692. img.onload = function () {
  7693. // no longer need to read the blob so it's revoked
  7694. URL.revokeObjectURL(url);
  7695. };
  7696. img.src = url;
  7697. newWindow.document.body.appendChild(img);
  7698. }
  7699. });
  7700. }
  7701. };
  7702. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7703. if (mimeType === void 0) { mimeType = "image/png"; }
  7704. var width;
  7705. var height;
  7706. // If a precision value is specified
  7707. if (size.precision) {
  7708. width = Math.round(engine.getRenderWidth() * size.precision);
  7709. height = Math.round(width / engine.getAspectRatio(camera));
  7710. }
  7711. else if (size.width && size.height) {
  7712. width = size.width;
  7713. height = size.height;
  7714. }
  7715. else if (size.width && !size.height) {
  7716. width = size.width;
  7717. height = Math.round(width / engine.getAspectRatio(camera));
  7718. }
  7719. else if (size.height && !size.width) {
  7720. height = size.height;
  7721. width = Math.round(height * engine.getAspectRatio(camera));
  7722. }
  7723. else if (!isNaN(size)) {
  7724. height = size;
  7725. width = size;
  7726. }
  7727. else {
  7728. Tools.Error("Invalid 'size' parameter !");
  7729. return;
  7730. }
  7731. if (!screenshotCanvas) {
  7732. screenshotCanvas = document.createElement('canvas');
  7733. }
  7734. screenshotCanvas.width = width;
  7735. screenshotCanvas.height = height;
  7736. var renderContext = screenshotCanvas.getContext("2d");
  7737. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7738. var newWidth = width;
  7739. var newHeight = newWidth / ratio;
  7740. if (newHeight > height) {
  7741. newHeight = height;
  7742. newWidth = newHeight * ratio;
  7743. }
  7744. var offsetX = Math.max(0, width - newWidth) / 2;
  7745. var offsetY = Math.max(0, height - newHeight) / 2;
  7746. var renderingCanvas = engine.getRenderingCanvas();
  7747. if (renderContext && renderingCanvas) {
  7748. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7749. }
  7750. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7751. };
  7752. /**
  7753. * Generates an image screenshot from the specified camera.
  7754. *
  7755. * @param engine The engine to use for rendering
  7756. * @param camera The camera to use for rendering
  7757. * @param size This parameter can be set to a single number or to an object with the
  7758. * following (optional) properties: precision, width, height. If a single number is passed,
  7759. * it will be used for both width and height. If an object is passed, the screenshot size
  7760. * will be derived from the parameters. The precision property is a multiplier allowing
  7761. * rendering at a higher or lower resolution.
  7762. * @param successCallback The callback receives a single parameter which contains the
  7763. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7764. * src parameter of an <img> to display it.
  7765. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7766. * Check your browser for supported MIME types.
  7767. * @param samples Texture samples (default: 1)
  7768. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7769. * @param fileName A name for for the downloaded file.
  7770. * @constructor
  7771. */
  7772. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7773. if (mimeType === void 0) { mimeType = "image/png"; }
  7774. if (samples === void 0) { samples = 1; }
  7775. if (antialiasing === void 0) { antialiasing = false; }
  7776. var width;
  7777. var height;
  7778. //If a precision value is specified
  7779. if (size.precision) {
  7780. width = Math.round(engine.getRenderWidth() * size.precision);
  7781. height = Math.round(width / engine.getAspectRatio(camera));
  7782. size = { width: width, height: height };
  7783. }
  7784. else if (size.width && size.height) {
  7785. width = size.width;
  7786. height = size.height;
  7787. }
  7788. else if (size.width && !size.height) {
  7789. width = size.width;
  7790. height = Math.round(width / engine.getAspectRatio(camera));
  7791. size = { width: width, height: height };
  7792. }
  7793. else if (size.height && !size.width) {
  7794. height = size.height;
  7795. width = Math.round(height * engine.getAspectRatio(camera));
  7796. size = { width: width, height: height };
  7797. }
  7798. else if (!isNaN(size)) {
  7799. height = size;
  7800. width = size;
  7801. }
  7802. else {
  7803. Tools.Error("Invalid 'size' parameter !");
  7804. return;
  7805. }
  7806. var scene = camera.getScene();
  7807. var previousCamera = null;
  7808. if (scene.activeCamera !== camera) {
  7809. previousCamera = scene.activeCamera;
  7810. scene.activeCamera = camera;
  7811. }
  7812. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7813. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7814. texture.renderList = null;
  7815. texture.samples = samples;
  7816. if (antialiasing) {
  7817. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7818. }
  7819. texture.onAfterRenderObservable.add(function () {
  7820. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7821. });
  7822. scene.incrementRenderId();
  7823. scene.resetCachedMaterial();
  7824. texture.render(true);
  7825. texture.dispose();
  7826. if (previousCamera) {
  7827. scene.activeCamera = previousCamera;
  7828. }
  7829. camera.getProjectionMatrix(true); // Force cache refresh;
  7830. };
  7831. // XHR response validator for local file scenario
  7832. Tools.ValidateXHRData = function (xhr, dataType) {
  7833. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7834. if (dataType === void 0) { dataType = 7; }
  7835. try {
  7836. if (dataType & 1) {
  7837. if (xhr.responseText && xhr.responseText.length > 0) {
  7838. return true;
  7839. }
  7840. else if (dataType === 1) {
  7841. return false;
  7842. }
  7843. }
  7844. if (dataType & 2) {
  7845. // Check header width and height since there is no "TGA" magic number
  7846. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7847. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7848. return true;
  7849. }
  7850. else if (dataType === 2) {
  7851. return false;
  7852. }
  7853. }
  7854. if (dataType & 4) {
  7855. // Check for the "DDS" magic number
  7856. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7857. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7858. return true;
  7859. }
  7860. else {
  7861. return false;
  7862. }
  7863. }
  7864. }
  7865. catch (e) {
  7866. // Global protection
  7867. }
  7868. return false;
  7869. };
  7870. /**
  7871. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7872. * Be aware Math.random() could cause collisions, but:
  7873. * "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"
  7874. */
  7875. Tools.RandomId = function () {
  7876. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7877. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7878. return v.toString(16);
  7879. });
  7880. };
  7881. /**
  7882. * Test if the given uri is a base64 string.
  7883. * @param uri The uri to test
  7884. * @return True if the uri is a base64 string or false otherwise.
  7885. */
  7886. Tools.IsBase64 = function (uri) {
  7887. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  7888. };
  7889. /**
  7890. * Decode the given base64 uri.
  7891. * @param uri The uri to decode
  7892. * @return The decoded base64 data.
  7893. */
  7894. Tools.DecodeBase64 = function (uri) {
  7895. var decodedString = atob(uri.split(",")[1]);
  7896. var bufferLength = decodedString.length;
  7897. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  7898. for (var i = 0; i < bufferLength; i++) {
  7899. bufferView[i] = decodedString.charCodeAt(i);
  7900. }
  7901. return bufferView.buffer;
  7902. };
  7903. Object.defineProperty(Tools, "NoneLogLevel", {
  7904. get: function () {
  7905. return Tools._NoneLogLevel;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(Tools, "MessageLogLevel", {
  7911. get: function () {
  7912. return Tools._MessageLogLevel;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Tools, "WarningLogLevel", {
  7918. get: function () {
  7919. return Tools._WarningLogLevel;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Tools, "ErrorLogLevel", {
  7925. get: function () {
  7926. return Tools._ErrorLogLevel;
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(Tools, "AllLogLevel", {
  7932. get: function () {
  7933. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Tools._AddLogEntry = function (entry) {
  7939. Tools._LogCache = entry + Tools._LogCache;
  7940. if (Tools.OnNewCacheEntry) {
  7941. Tools.OnNewCacheEntry(entry);
  7942. }
  7943. };
  7944. Tools._FormatMessage = function (message) {
  7945. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7946. var date = new Date();
  7947. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7948. };
  7949. Tools._LogDisabled = function (message) {
  7950. // nothing to do
  7951. };
  7952. Tools._LogEnabled = function (message) {
  7953. var formattedMessage = Tools._FormatMessage(message);
  7954. console.log("BJS - " + formattedMessage);
  7955. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7956. Tools._AddLogEntry(entry);
  7957. };
  7958. Tools._WarnDisabled = function (message) {
  7959. // nothing to do
  7960. };
  7961. Tools._WarnEnabled = function (message) {
  7962. var formattedMessage = Tools._FormatMessage(message);
  7963. console.warn("BJS - " + formattedMessage);
  7964. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7965. Tools._AddLogEntry(entry);
  7966. };
  7967. Tools._ErrorDisabled = function (message) {
  7968. // nothing to do
  7969. };
  7970. Tools._ErrorEnabled = function (message) {
  7971. Tools.errorsCount++;
  7972. var formattedMessage = Tools._FormatMessage(message);
  7973. console.error("BJS - " + formattedMessage);
  7974. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7975. Tools._AddLogEntry(entry);
  7976. };
  7977. Object.defineProperty(Tools, "LogCache", {
  7978. get: function () {
  7979. return Tools._LogCache;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Tools.ClearLogCache = function () {
  7985. Tools._LogCache = "";
  7986. Tools.errorsCount = 0;
  7987. };
  7988. Object.defineProperty(Tools, "LogLevels", {
  7989. set: function (level) {
  7990. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7991. Tools.Log = Tools._LogEnabled;
  7992. }
  7993. else {
  7994. Tools.Log = Tools._LogDisabled;
  7995. }
  7996. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7997. Tools.Warn = Tools._WarnEnabled;
  7998. }
  7999. else {
  8000. Tools.Warn = Tools._WarnDisabled;
  8001. }
  8002. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8003. Tools.Error = Tools._ErrorEnabled;
  8004. }
  8005. else {
  8006. Tools.Error = Tools._ErrorDisabled;
  8007. }
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Tools.IsWindowObjectExist = function () {
  8013. return (typeof window) !== "undefined";
  8014. };
  8015. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8016. get: function () {
  8017. return Tools._PerformanceNoneLogLevel;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8023. get: function () {
  8024. return Tools._PerformanceUserMarkLogLevel;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8030. get: function () {
  8031. return Tools._PerformanceConsoleLogLevel;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8037. set: function (level) {
  8038. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8039. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8040. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8041. return;
  8042. }
  8043. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8044. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8045. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8046. return;
  8047. }
  8048. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8049. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8055. };
  8056. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8057. };
  8058. Tools._StartUserMark = function (counterName, condition) {
  8059. if (condition === void 0) { condition = true; }
  8060. if (!Tools._performance) {
  8061. if (!Tools.IsWindowObjectExist()) {
  8062. return;
  8063. }
  8064. Tools._performance = window.performance;
  8065. }
  8066. if (!condition || !Tools._performance.mark) {
  8067. return;
  8068. }
  8069. Tools._performance.mark(counterName + "-Begin");
  8070. };
  8071. Tools._EndUserMark = function (counterName, condition) {
  8072. if (condition === void 0) { condition = true; }
  8073. if (!condition || !Tools._performance.mark) {
  8074. return;
  8075. }
  8076. Tools._performance.mark(counterName + "-End");
  8077. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8078. };
  8079. Tools._StartPerformanceConsole = function (counterName, condition) {
  8080. if (condition === void 0) { condition = true; }
  8081. if (!condition) {
  8082. return;
  8083. }
  8084. Tools._StartUserMark(counterName, condition);
  8085. if (console.time) {
  8086. console.time(counterName);
  8087. }
  8088. };
  8089. Tools._EndPerformanceConsole = function (counterName, condition) {
  8090. if (condition === void 0) { condition = true; }
  8091. if (!condition) {
  8092. return;
  8093. }
  8094. Tools._EndUserMark(counterName, condition);
  8095. if (console.time) {
  8096. console.timeEnd(counterName);
  8097. }
  8098. };
  8099. Object.defineProperty(Tools, "Now", {
  8100. get: function () {
  8101. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8102. return window.performance.now();
  8103. }
  8104. return new Date().getTime();
  8105. },
  8106. enumerable: true,
  8107. configurable: true
  8108. });
  8109. /**
  8110. * This method will return the name of the class used to create the instance of the given object.
  8111. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8112. * @param object the object to get the class name from
  8113. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8114. */
  8115. Tools.GetClassName = function (object, isType) {
  8116. if (isType === void 0) { isType = false; }
  8117. var name = null;
  8118. if (!isType && object.getClassName) {
  8119. name = object.getClassName();
  8120. }
  8121. else {
  8122. if (object instanceof Object) {
  8123. var classObj = isType ? object : Object.getPrototypeOf(object);
  8124. name = classObj.constructor["__bjsclassName__"];
  8125. }
  8126. if (!name) {
  8127. name = typeof object;
  8128. }
  8129. }
  8130. return name;
  8131. };
  8132. Tools.First = function (array, predicate) {
  8133. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8134. var el = array_1[_i];
  8135. if (predicate(el)) {
  8136. return el;
  8137. }
  8138. }
  8139. return null;
  8140. };
  8141. /**
  8142. * This method will return the name of the full name of the class, including its owning module (if any).
  8143. * 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).
  8144. * @param object the object to get the class name from
  8145. * @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.
  8146. */
  8147. Tools.getFullClassName = function (object, isType) {
  8148. if (isType === void 0) { isType = false; }
  8149. var className = null;
  8150. var moduleName = null;
  8151. if (!isType && object.getClassName) {
  8152. className = object.getClassName();
  8153. }
  8154. else {
  8155. if (object instanceof Object) {
  8156. var classObj = isType ? object : Object.getPrototypeOf(object);
  8157. className = classObj.constructor["__bjsclassName__"];
  8158. moduleName = classObj.constructor["__bjsmoduleName__"];
  8159. }
  8160. if (!className) {
  8161. className = typeof object;
  8162. }
  8163. }
  8164. if (!className) {
  8165. return null;
  8166. }
  8167. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8168. };
  8169. /**
  8170. * 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.
  8171. * @param array
  8172. */
  8173. Tools.arrayOrStringFeeder = function (array) {
  8174. return function (index) {
  8175. if (index >= array.length) {
  8176. return null;
  8177. }
  8178. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8179. if (val && val.getHashCode) {
  8180. val = val.getHashCode();
  8181. }
  8182. if (typeof val === "string") {
  8183. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8184. }
  8185. return val;
  8186. };
  8187. };
  8188. /**
  8189. * Compute the hashCode of a stream of number
  8190. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8191. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8192. * @return the hash code computed
  8193. */
  8194. Tools.hashCodeFromStream = function (feeder) {
  8195. // Based from here: http://stackoverflow.com/a/7616484/802124
  8196. var hash = 0;
  8197. var index = 0;
  8198. var chr = feeder(index++);
  8199. while (chr != null) {
  8200. hash = ((hash << 5) - hash) + chr;
  8201. hash |= 0; // Convert to 32bit integer
  8202. chr = feeder(index++);
  8203. }
  8204. return hash;
  8205. };
  8206. Tools.BaseUrl = "";
  8207. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8208. /**
  8209. * Default behaviour for cors in the application.
  8210. * It can be a string if the expected behavior is identical in the entire app.
  8211. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8212. */
  8213. Tools.CorsBehavior = "anonymous";
  8214. Tools.UseFallbackTexture = true;
  8215. /**
  8216. * Use this object to register external classes like custom textures or material
  8217. * to allow the laoders to instantiate them
  8218. */
  8219. Tools.RegisteredExternalClasses = {};
  8220. // Used in case of a texture loading problem
  8221. 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";
  8222. Tools.PreprocessUrl = function (url) {
  8223. return url;
  8224. };
  8225. // Logs
  8226. Tools._NoneLogLevel = 0;
  8227. Tools._MessageLogLevel = 1;
  8228. Tools._WarningLogLevel = 2;
  8229. Tools._ErrorLogLevel = 4;
  8230. Tools._LogCache = "";
  8231. Tools.errorsCount = 0;
  8232. Tools.Log = Tools._LogEnabled;
  8233. Tools.Warn = Tools._WarnEnabled;
  8234. Tools.Error = Tools._ErrorEnabled;
  8235. // Performances
  8236. Tools._PerformanceNoneLogLevel = 0;
  8237. Tools._PerformanceUserMarkLogLevel = 1;
  8238. Tools._PerformanceConsoleLogLevel = 2;
  8239. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8240. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8241. return Tools;
  8242. }());
  8243. BABYLON.Tools = Tools;
  8244. /**
  8245. * This class is used to track a performance counter which is number based.
  8246. * The user has access to many properties which give statistics of different nature
  8247. *
  8248. * The implementer can track two kinds of Performance Counter: time and count
  8249. * 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.
  8250. * 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.
  8251. */
  8252. var PerfCounter = /** @class */ (function () {
  8253. function PerfCounter() {
  8254. this._startMonitoringTime = 0;
  8255. this._min = 0;
  8256. this._max = 0;
  8257. this._average = 0;
  8258. this._lastSecAverage = 0;
  8259. this._current = 0;
  8260. this._totalValueCount = 0;
  8261. this._totalAccumulated = 0;
  8262. this._lastSecAccumulated = 0;
  8263. this._lastSecTime = 0;
  8264. this._lastSecValueCount = 0;
  8265. }
  8266. Object.defineProperty(PerfCounter.prototype, "min", {
  8267. /**
  8268. * Returns the smallest value ever
  8269. */
  8270. get: function () {
  8271. return this._min;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(PerfCounter.prototype, "max", {
  8277. /**
  8278. * Returns the biggest value ever
  8279. */
  8280. get: function () {
  8281. return this._max;
  8282. },
  8283. enumerable: true,
  8284. configurable: true
  8285. });
  8286. Object.defineProperty(PerfCounter.prototype, "average", {
  8287. /**
  8288. * Returns the average value since the performance counter is running
  8289. */
  8290. get: function () {
  8291. return this._average;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8297. /**
  8298. * Returns the average value of the last second the counter was monitored
  8299. */
  8300. get: function () {
  8301. return this._lastSecAverage;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(PerfCounter.prototype, "current", {
  8307. /**
  8308. * Returns the current value
  8309. */
  8310. get: function () {
  8311. return this._current;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(PerfCounter.prototype, "total", {
  8317. get: function () {
  8318. return this._totalAccumulated;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(PerfCounter.prototype, "count", {
  8324. get: function () {
  8325. return this._totalValueCount;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. /**
  8331. * Call this method to start monitoring a new frame.
  8332. * 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.
  8333. */
  8334. PerfCounter.prototype.fetchNewFrame = function () {
  8335. this._totalValueCount++;
  8336. this._current = 0;
  8337. this._lastSecValueCount++;
  8338. };
  8339. /**
  8340. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8341. * @param newCount the count value to add to the monitored count
  8342. * @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.
  8343. */
  8344. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8345. if (!PerfCounter.Enabled) {
  8346. return;
  8347. }
  8348. this._current += newCount;
  8349. if (fetchResult) {
  8350. this._fetchResult();
  8351. }
  8352. };
  8353. /**
  8354. * Start monitoring this performance counter
  8355. */
  8356. PerfCounter.prototype.beginMonitoring = function () {
  8357. if (!PerfCounter.Enabled) {
  8358. return;
  8359. }
  8360. this._startMonitoringTime = Tools.Now;
  8361. };
  8362. /**
  8363. * Compute the time lapsed since the previous beginMonitoring() call.
  8364. * @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
  8365. */
  8366. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8367. if (newFrame === void 0) { newFrame = true; }
  8368. if (!PerfCounter.Enabled) {
  8369. return;
  8370. }
  8371. if (newFrame) {
  8372. this.fetchNewFrame();
  8373. }
  8374. var currentTime = Tools.Now;
  8375. this._current = currentTime - this._startMonitoringTime;
  8376. if (newFrame) {
  8377. this._fetchResult();
  8378. }
  8379. };
  8380. PerfCounter.prototype._fetchResult = function () {
  8381. this._totalAccumulated += this._current;
  8382. this._lastSecAccumulated += this._current;
  8383. // Min/Max update
  8384. this._min = Math.min(this._min, this._current);
  8385. this._max = Math.max(this._max, this._current);
  8386. this._average = this._totalAccumulated / this._totalValueCount;
  8387. // Reset last sec?
  8388. var now = Tools.Now;
  8389. if ((now - this._lastSecTime) > 1000) {
  8390. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8391. this._lastSecTime = now;
  8392. this._lastSecAccumulated = 0;
  8393. this._lastSecValueCount = 0;
  8394. }
  8395. };
  8396. PerfCounter.Enabled = true;
  8397. return PerfCounter;
  8398. }());
  8399. BABYLON.PerfCounter = PerfCounter;
  8400. /**
  8401. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8402. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8403. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8404. * @param name The name of the class, case should be preserved
  8405. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8406. */
  8407. function className(name, module) {
  8408. return function (target) {
  8409. target["__bjsclassName__"] = name;
  8410. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8411. };
  8412. }
  8413. BABYLON.className = className;
  8414. /**
  8415. * An implementation of a loop for asynchronous functions.
  8416. */
  8417. var AsyncLoop = /** @class */ (function () {
  8418. /**
  8419. * Constroctor.
  8420. * @param iterations the number of iterations.
  8421. * @param _fn the function to run each iteration
  8422. * @param _successCallback the callback that will be called upon succesful execution
  8423. * @param offset starting offset.
  8424. */
  8425. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8426. if (offset === void 0) { offset = 0; }
  8427. this.iterations = iterations;
  8428. this._fn = _fn;
  8429. this._successCallback = _successCallback;
  8430. this.index = offset - 1;
  8431. this._done = false;
  8432. }
  8433. /**
  8434. * Execute the next iteration. Must be called after the last iteration was finished.
  8435. */
  8436. AsyncLoop.prototype.executeNext = function () {
  8437. if (!this._done) {
  8438. if (this.index + 1 < this.iterations) {
  8439. ++this.index;
  8440. this._fn(this);
  8441. }
  8442. else {
  8443. this.breakLoop();
  8444. }
  8445. }
  8446. };
  8447. /**
  8448. * Break the loop and run the success callback.
  8449. */
  8450. AsyncLoop.prototype.breakLoop = function () {
  8451. this._done = true;
  8452. this._successCallback();
  8453. };
  8454. /**
  8455. * Helper function
  8456. */
  8457. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8458. if (offset === void 0) { offset = 0; }
  8459. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8460. loop.executeNext();
  8461. return loop;
  8462. };
  8463. /**
  8464. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8465. * @param iterations total number of iterations
  8466. * @param syncedIterations number of synchronous iterations in each async iteration.
  8467. * @param fn the function to call each iteration.
  8468. * @param callback a success call back that will be called when iterating stops.
  8469. * @param breakFunction a break condition (optional)
  8470. * @param timeout timeout settings for the setTimeout function. default - 0.
  8471. * @constructor
  8472. */
  8473. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8474. if (timeout === void 0) { timeout = 0; }
  8475. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8476. if (breakFunction && breakFunction())
  8477. loop.breakLoop();
  8478. else {
  8479. setTimeout(function () {
  8480. for (var i = 0; i < syncedIterations; ++i) {
  8481. var iteration = (loop.index * syncedIterations) + i;
  8482. if (iteration >= iterations)
  8483. break;
  8484. fn(iteration);
  8485. if (breakFunction && breakFunction()) {
  8486. loop.breakLoop();
  8487. break;
  8488. }
  8489. }
  8490. loop.executeNext();
  8491. }, timeout);
  8492. }
  8493. }, callback);
  8494. };
  8495. return AsyncLoop;
  8496. }());
  8497. BABYLON.AsyncLoop = AsyncLoop;
  8498. })(BABYLON || (BABYLON = {}));
  8499. //# sourceMappingURL=babylon.tools.js.map
  8500. var BABYLON;
  8501. (function (BABYLON) {
  8502. var PromiseStates;
  8503. (function (PromiseStates) {
  8504. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8505. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8506. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8507. })(PromiseStates || (PromiseStates = {}));
  8508. var FulFillmentAgregator = /** @class */ (function () {
  8509. function FulFillmentAgregator() {
  8510. this.count = 0;
  8511. this.target = 0;
  8512. this.results = [];
  8513. }
  8514. return FulFillmentAgregator;
  8515. }());
  8516. var InternalPromise = /** @class */ (function () {
  8517. function InternalPromise(resolver) {
  8518. var _this = this;
  8519. this._state = PromiseStates.Pending;
  8520. this._children = new Array();
  8521. this._rejectWasConsumed = false;
  8522. if (!resolver) {
  8523. return;
  8524. }
  8525. try {
  8526. resolver(function (value) {
  8527. _this._resolve(value);
  8528. }, function (reason) {
  8529. _this._reject(reason);
  8530. });
  8531. }
  8532. catch (e) {
  8533. this._reject(e.message);
  8534. }
  8535. }
  8536. Object.defineProperty(InternalPromise.prototype, "state", {
  8537. get: function () {
  8538. return this._state;
  8539. },
  8540. enumerable: true,
  8541. configurable: true
  8542. });
  8543. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8544. get: function () {
  8545. return this._state === PromiseStates.Fulfilled;
  8546. },
  8547. enumerable: true,
  8548. configurable: true
  8549. });
  8550. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8551. get: function () {
  8552. return this._state === PromiseStates.Rejected;
  8553. },
  8554. enumerable: true,
  8555. configurable: true
  8556. });
  8557. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8558. get: function () {
  8559. return this._state === PromiseStates.Pending;
  8560. },
  8561. enumerable: true,
  8562. configurable: true
  8563. });
  8564. InternalPromise.prototype.value = function () {
  8565. if (!this.isFulfilled) {
  8566. throw new Error("Promise is not fulfilled");
  8567. }
  8568. return this._result;
  8569. };
  8570. InternalPromise.prototype.reason = function () {
  8571. if (!this.isRejected) {
  8572. throw new Error("Promise is not rejected");
  8573. }
  8574. return this._reason;
  8575. };
  8576. InternalPromise.prototype.catch = function (onRejected) {
  8577. return this.then(undefined, onRejected);
  8578. };
  8579. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8580. var newPromise = new InternalPromise();
  8581. newPromise._onFulfilled = onFulfilled;
  8582. newPromise._onRejected = onRejected;
  8583. // Composition
  8584. this._children.push(newPromise);
  8585. if (this._state !== PromiseStates.Pending) {
  8586. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8587. var returnedValue = newPromise._resolve(this._result);
  8588. if (returnedValue !== undefined && returnedValue !== null) {
  8589. if (returnedValue._state !== undefined) {
  8590. var returnedPromise = returnedValue;
  8591. newPromise._children.push(returnedPromise);
  8592. newPromise = returnedPromise;
  8593. }
  8594. else {
  8595. newPromise._result = returnedValue;
  8596. }
  8597. }
  8598. }
  8599. else {
  8600. newPromise._reject(this._reason);
  8601. }
  8602. }
  8603. return newPromise;
  8604. };
  8605. InternalPromise.prototype._moveChildren = function (children) {
  8606. this._children = children.splice(0, children.length);
  8607. if (this.isFulfilled) {
  8608. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8609. var child = _a[_i];
  8610. child._resolve(this._result);
  8611. }
  8612. }
  8613. else if (this.isRejected) {
  8614. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8615. var child = _c[_b];
  8616. child._reject(this._reason);
  8617. }
  8618. }
  8619. };
  8620. InternalPromise.prototype._resolve = function (value) {
  8621. try {
  8622. this._state = PromiseStates.Fulfilled;
  8623. this._result = value;
  8624. var returnedValue = null;
  8625. if (this._onFulfilled) {
  8626. returnedValue = this._onFulfilled(value);
  8627. }
  8628. if (returnedValue !== undefined && returnedValue !== null) {
  8629. if (returnedValue._state !== undefined) {
  8630. // Transmit children
  8631. var returnedPromise = returnedValue;
  8632. returnedPromise._moveChildren(this._children);
  8633. }
  8634. }
  8635. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8636. var child = _a[_i];
  8637. child._resolve(value);
  8638. }
  8639. return returnedValue;
  8640. }
  8641. catch (e) {
  8642. this._reject(e.message);
  8643. }
  8644. return null;
  8645. };
  8646. InternalPromise.prototype._reject = function (reason) {
  8647. this._state = PromiseStates.Rejected;
  8648. this._reason = reason;
  8649. if (this._onRejected) {
  8650. this._onRejected(reason);
  8651. this._rejectWasConsumed = true;
  8652. }
  8653. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8654. var child = _a[_i];
  8655. if (this._rejectWasConsumed) {
  8656. child._resolve(null);
  8657. }
  8658. else {
  8659. child._reject(reason);
  8660. }
  8661. }
  8662. };
  8663. InternalPromise.resolve = function (value) {
  8664. var newPromise = new InternalPromise();
  8665. newPromise._resolve(value);
  8666. return newPromise;
  8667. };
  8668. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8669. promise.then(function (value) {
  8670. agregator.results[index] = value;
  8671. agregator.count++;
  8672. if (agregator.count === agregator.target) {
  8673. agregator.rootPromise._resolve(agregator.results);
  8674. }
  8675. return null;
  8676. }, function (reason) {
  8677. if (!agregator.rootPromise.isRejected) {
  8678. agregator.rootPromise._reject(reason);
  8679. }
  8680. });
  8681. };
  8682. InternalPromise.all = function (promises) {
  8683. var newPromise = new InternalPromise();
  8684. var agregator = new FulFillmentAgregator();
  8685. agregator.target = promises.length;
  8686. agregator.rootPromise = newPromise;
  8687. for (var index = 0; index < promises.length; index++) {
  8688. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8689. }
  8690. return newPromise;
  8691. };
  8692. return InternalPromise;
  8693. }());
  8694. /**
  8695. * Helper class that provides a small promise polyfill
  8696. */
  8697. var PromisePolyfill = /** @class */ (function () {
  8698. function PromisePolyfill() {
  8699. }
  8700. /**
  8701. * Static function used to check if the polyfill is required
  8702. * If this is the case then the function will inject the polyfill to window.Promise
  8703. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8704. */
  8705. PromisePolyfill.Apply = function (force) {
  8706. if (force === void 0) { force = false; }
  8707. if (force || typeof Promise === 'undefined') {
  8708. var root = window;
  8709. root.Promise = InternalPromise;
  8710. }
  8711. };
  8712. return PromisePolyfill;
  8713. }());
  8714. BABYLON.PromisePolyfill = PromisePolyfill;
  8715. })(BABYLON || (BABYLON = {}));
  8716. //# sourceMappingURL=babylon.promise.js.map
  8717. var BABYLON;
  8718. (function (BABYLON) {
  8719. var _AlphaState = /** @class */ (function () {
  8720. /**
  8721. * Initializes the state.
  8722. */
  8723. function _AlphaState() {
  8724. this._isAlphaBlendDirty = false;
  8725. this._isBlendFunctionParametersDirty = false;
  8726. this._isBlendEquationParametersDirty = false;
  8727. this._isBlendConstantsDirty = false;
  8728. this._alphaBlend = false;
  8729. this._blendFunctionParameters = new Array(4);
  8730. this._blendEquationParameters = new Array(2);
  8731. this._blendConstants = new Array(4);
  8732. this.reset();
  8733. }
  8734. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8735. get: function () {
  8736. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8742. get: function () {
  8743. return this._alphaBlend;
  8744. },
  8745. set: function (value) {
  8746. if (this._alphaBlend === value) {
  8747. return;
  8748. }
  8749. this._alphaBlend = value;
  8750. this._isAlphaBlendDirty = true;
  8751. },
  8752. enumerable: true,
  8753. configurable: true
  8754. });
  8755. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8756. if (this._blendConstants[0] === r &&
  8757. this._blendConstants[1] === g &&
  8758. this._blendConstants[2] === b &&
  8759. this._blendConstants[3] === a) {
  8760. return;
  8761. }
  8762. this._blendConstants[0] = r;
  8763. this._blendConstants[1] = g;
  8764. this._blendConstants[2] = b;
  8765. this._blendConstants[3] = a;
  8766. this._isBlendConstantsDirty = true;
  8767. };
  8768. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8769. if (this._blendFunctionParameters[0] === value0 &&
  8770. this._blendFunctionParameters[1] === value1 &&
  8771. this._blendFunctionParameters[2] === value2 &&
  8772. this._blendFunctionParameters[3] === value3) {
  8773. return;
  8774. }
  8775. this._blendFunctionParameters[0] = value0;
  8776. this._blendFunctionParameters[1] = value1;
  8777. this._blendFunctionParameters[2] = value2;
  8778. this._blendFunctionParameters[3] = value3;
  8779. this._isBlendFunctionParametersDirty = true;
  8780. };
  8781. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8782. if (this._blendEquationParameters[0] === rgb &&
  8783. this._blendEquationParameters[1] === alpha) {
  8784. return;
  8785. }
  8786. this._blendEquationParameters[0] = rgb;
  8787. this._blendEquationParameters[1] = alpha;
  8788. this._isBlendEquationParametersDirty = true;
  8789. };
  8790. _AlphaState.prototype.reset = function () {
  8791. this._alphaBlend = false;
  8792. this._blendFunctionParameters[0] = null;
  8793. this._blendFunctionParameters[1] = null;
  8794. this._blendFunctionParameters[2] = null;
  8795. this._blendFunctionParameters[3] = null;
  8796. this._blendEquationParameters[0] = null;
  8797. this._blendEquationParameters[1] = null;
  8798. this._blendConstants[0] = null;
  8799. this._blendConstants[1] = null;
  8800. this._blendConstants[2] = null;
  8801. this._blendConstants[3] = null;
  8802. this._isAlphaBlendDirty = true;
  8803. this._isBlendFunctionParametersDirty = false;
  8804. this._isBlendEquationParametersDirty = false;
  8805. this._isBlendConstantsDirty = false;
  8806. };
  8807. _AlphaState.prototype.apply = function (gl) {
  8808. if (!this.isDirty) {
  8809. return;
  8810. }
  8811. // Alpha blend
  8812. if (this._isAlphaBlendDirty) {
  8813. if (this._alphaBlend) {
  8814. gl.enable(gl.BLEND);
  8815. }
  8816. else {
  8817. gl.disable(gl.BLEND);
  8818. }
  8819. this._isAlphaBlendDirty = false;
  8820. }
  8821. // Alpha function
  8822. if (this._isBlendFunctionParametersDirty) {
  8823. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8824. this._isBlendFunctionParametersDirty = false;
  8825. }
  8826. // Alpha equation
  8827. if (this._isBlendEquationParametersDirty) {
  8828. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8829. this._isBlendEquationParametersDirty = false;
  8830. }
  8831. // Constants
  8832. if (this._isBlendConstantsDirty) {
  8833. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8834. this._isBlendConstantsDirty = false;
  8835. }
  8836. };
  8837. return _AlphaState;
  8838. }());
  8839. BABYLON._AlphaState = _AlphaState;
  8840. })(BABYLON || (BABYLON = {}));
  8841. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8842. var BABYLON;
  8843. (function (BABYLON) {
  8844. var _DepthCullingState = /** @class */ (function () {
  8845. /**
  8846. * Initializes the state.
  8847. */
  8848. function _DepthCullingState() {
  8849. this._isDepthTestDirty = false;
  8850. this._isDepthMaskDirty = false;
  8851. this._isDepthFuncDirty = false;
  8852. this._isCullFaceDirty = false;
  8853. this._isCullDirty = false;
  8854. this._isZOffsetDirty = false;
  8855. this._isFrontFaceDirty = false;
  8856. this.reset();
  8857. }
  8858. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8859. get: function () {
  8860. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8861. },
  8862. enumerable: true,
  8863. configurable: true
  8864. });
  8865. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8866. get: function () {
  8867. return this._zOffset;
  8868. },
  8869. set: function (value) {
  8870. if (this._zOffset === value) {
  8871. return;
  8872. }
  8873. this._zOffset = value;
  8874. this._isZOffsetDirty = true;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8880. get: function () {
  8881. return this._cullFace;
  8882. },
  8883. set: function (value) {
  8884. if (this._cullFace === value) {
  8885. return;
  8886. }
  8887. this._cullFace = value;
  8888. this._isCullFaceDirty = true;
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8894. get: function () {
  8895. return this._cull;
  8896. },
  8897. set: function (value) {
  8898. if (this._cull === value) {
  8899. return;
  8900. }
  8901. this._cull = value;
  8902. this._isCullDirty = true;
  8903. },
  8904. enumerable: true,
  8905. configurable: true
  8906. });
  8907. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8908. get: function () {
  8909. return this._depthFunc;
  8910. },
  8911. set: function (value) {
  8912. if (this._depthFunc === value) {
  8913. return;
  8914. }
  8915. this._depthFunc = value;
  8916. this._isDepthFuncDirty = true;
  8917. },
  8918. enumerable: true,
  8919. configurable: true
  8920. });
  8921. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8922. get: function () {
  8923. return this._depthMask;
  8924. },
  8925. set: function (value) {
  8926. if (this._depthMask === value) {
  8927. return;
  8928. }
  8929. this._depthMask = value;
  8930. this._isDepthMaskDirty = true;
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8936. get: function () {
  8937. return this._depthTest;
  8938. },
  8939. set: function (value) {
  8940. if (this._depthTest === value) {
  8941. return;
  8942. }
  8943. this._depthTest = value;
  8944. this._isDepthTestDirty = true;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8950. get: function () {
  8951. return this._frontFace;
  8952. },
  8953. set: function (value) {
  8954. if (this._frontFace === value) {
  8955. return;
  8956. }
  8957. this._frontFace = value;
  8958. this._isFrontFaceDirty = true;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. _DepthCullingState.prototype.reset = function () {
  8964. this._depthMask = true;
  8965. this._depthTest = true;
  8966. this._depthFunc = null;
  8967. this._cullFace = null;
  8968. this._cull = null;
  8969. this._zOffset = 0;
  8970. this._frontFace = null;
  8971. this._isDepthTestDirty = true;
  8972. this._isDepthMaskDirty = true;
  8973. this._isDepthFuncDirty = false;
  8974. this._isCullFaceDirty = false;
  8975. this._isCullDirty = false;
  8976. this._isZOffsetDirty = false;
  8977. this._isFrontFaceDirty = false;
  8978. };
  8979. _DepthCullingState.prototype.apply = function (gl) {
  8980. if (!this.isDirty) {
  8981. return;
  8982. }
  8983. // Cull
  8984. if (this._isCullDirty) {
  8985. if (this.cull) {
  8986. gl.enable(gl.CULL_FACE);
  8987. }
  8988. else {
  8989. gl.disable(gl.CULL_FACE);
  8990. }
  8991. this._isCullDirty = false;
  8992. }
  8993. // Cull face
  8994. if (this._isCullFaceDirty) {
  8995. gl.cullFace(this.cullFace);
  8996. this._isCullFaceDirty = false;
  8997. }
  8998. // Depth mask
  8999. if (this._isDepthMaskDirty) {
  9000. gl.depthMask(this.depthMask);
  9001. this._isDepthMaskDirty = false;
  9002. }
  9003. // Depth test
  9004. if (this._isDepthTestDirty) {
  9005. if (this.depthTest) {
  9006. gl.enable(gl.DEPTH_TEST);
  9007. }
  9008. else {
  9009. gl.disable(gl.DEPTH_TEST);
  9010. }
  9011. this._isDepthTestDirty = false;
  9012. }
  9013. // Depth func
  9014. if (this._isDepthFuncDirty) {
  9015. gl.depthFunc(this.depthFunc);
  9016. this._isDepthFuncDirty = false;
  9017. }
  9018. // zOffset
  9019. if (this._isZOffsetDirty) {
  9020. if (this.zOffset) {
  9021. gl.enable(gl.POLYGON_OFFSET_FILL);
  9022. gl.polygonOffset(this.zOffset, 0);
  9023. }
  9024. else {
  9025. gl.disable(gl.POLYGON_OFFSET_FILL);
  9026. }
  9027. this._isZOffsetDirty = false;
  9028. }
  9029. // Front face
  9030. if (this._isFrontFaceDirty) {
  9031. gl.frontFace(this.frontFace);
  9032. this._isFrontFaceDirty = false;
  9033. }
  9034. };
  9035. return _DepthCullingState;
  9036. }());
  9037. BABYLON._DepthCullingState = _DepthCullingState;
  9038. })(BABYLON || (BABYLON = {}));
  9039. //# sourceMappingURL=babylon.depthCullingState.js.map
  9040. var BABYLON;
  9041. (function (BABYLON) {
  9042. var _StencilState = /** @class */ (function () {
  9043. function _StencilState() {
  9044. this._isStencilTestDirty = false;
  9045. this._isStencilMaskDirty = false;
  9046. this._isStencilFuncDirty = false;
  9047. this._isStencilOpDirty = false;
  9048. this.reset();
  9049. }
  9050. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9051. get: function () {
  9052. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9053. },
  9054. enumerable: true,
  9055. configurable: true
  9056. });
  9057. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9058. get: function () {
  9059. return this._stencilFunc;
  9060. },
  9061. set: function (value) {
  9062. if (this._stencilFunc === value) {
  9063. return;
  9064. }
  9065. this._stencilFunc = value;
  9066. this._isStencilFuncDirty = true;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9072. get: function () {
  9073. return this._stencilFuncRef;
  9074. },
  9075. set: function (value) {
  9076. if (this._stencilFuncRef === value) {
  9077. return;
  9078. }
  9079. this._stencilFuncRef = value;
  9080. this._isStencilFuncDirty = true;
  9081. },
  9082. enumerable: true,
  9083. configurable: true
  9084. });
  9085. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9086. get: function () {
  9087. return this._stencilFuncMask;
  9088. },
  9089. set: function (value) {
  9090. if (this._stencilFuncMask === value) {
  9091. return;
  9092. }
  9093. this._stencilFuncMask = value;
  9094. this._isStencilFuncDirty = true;
  9095. },
  9096. enumerable: true,
  9097. configurable: true
  9098. });
  9099. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9100. get: function () {
  9101. return this._stencilOpStencilFail;
  9102. },
  9103. set: function (value) {
  9104. if (this._stencilOpStencilFail === value) {
  9105. return;
  9106. }
  9107. this._stencilOpStencilFail = value;
  9108. this._isStencilOpDirty = true;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9114. get: function () {
  9115. return this._stencilOpDepthFail;
  9116. },
  9117. set: function (value) {
  9118. if (this._stencilOpDepthFail === value) {
  9119. return;
  9120. }
  9121. this._stencilOpDepthFail = value;
  9122. this._isStencilOpDirty = true;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9128. get: function () {
  9129. return this._stencilOpStencilDepthPass;
  9130. },
  9131. set: function (value) {
  9132. if (this._stencilOpStencilDepthPass === value) {
  9133. return;
  9134. }
  9135. this._stencilOpStencilDepthPass = value;
  9136. this._isStencilOpDirty = true;
  9137. },
  9138. enumerable: true,
  9139. configurable: true
  9140. });
  9141. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9142. get: function () {
  9143. return this._stencilMask;
  9144. },
  9145. set: function (value) {
  9146. if (this._stencilMask === value) {
  9147. return;
  9148. }
  9149. this._stencilMask = value;
  9150. this._isStencilMaskDirty = true;
  9151. },
  9152. enumerable: true,
  9153. configurable: true
  9154. });
  9155. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9156. get: function () {
  9157. return this._stencilTest;
  9158. },
  9159. set: function (value) {
  9160. if (this._stencilTest === value) {
  9161. return;
  9162. }
  9163. this._stencilTest = value;
  9164. this._isStencilTestDirty = true;
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. _StencilState.prototype.reset = function () {
  9170. this._stencilTest = false;
  9171. this._stencilMask = 0xFF;
  9172. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9173. this._stencilFuncRef = 1;
  9174. this._stencilFuncMask = 0xFF;
  9175. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9176. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9177. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9178. this._isStencilTestDirty = true;
  9179. this._isStencilMaskDirty = true;
  9180. this._isStencilFuncDirty = true;
  9181. this._isStencilOpDirty = true;
  9182. };
  9183. _StencilState.prototype.apply = function (gl) {
  9184. if (!this.isDirty) {
  9185. return;
  9186. }
  9187. // Stencil test
  9188. if (this._isStencilTestDirty) {
  9189. if (this.stencilTest) {
  9190. gl.enable(gl.STENCIL_TEST);
  9191. }
  9192. else {
  9193. gl.disable(gl.STENCIL_TEST);
  9194. }
  9195. this._isStencilTestDirty = false;
  9196. }
  9197. // Stencil mask
  9198. if (this._isStencilMaskDirty) {
  9199. gl.stencilMask(this.stencilMask);
  9200. this._isStencilMaskDirty = false;
  9201. }
  9202. // Stencil func
  9203. if (this._isStencilFuncDirty) {
  9204. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9205. this._isStencilFuncDirty = false;
  9206. }
  9207. // Stencil op
  9208. if (this._isStencilOpDirty) {
  9209. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9210. this._isStencilOpDirty = false;
  9211. }
  9212. };
  9213. return _StencilState;
  9214. }());
  9215. BABYLON._StencilState = _StencilState;
  9216. })(BABYLON || (BABYLON = {}));
  9217. //# sourceMappingURL=babylon.stencilState.js.map
  9218. var BABYLON;
  9219. (function (BABYLON) {
  9220. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9221. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9222. };
  9223. var compileRawShader = function (gl, source, type) {
  9224. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9225. gl.shaderSource(shader, source);
  9226. gl.compileShader(shader);
  9227. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9228. var log = gl.getShaderInfoLog(shader);
  9229. if (log) {
  9230. throw new Error(log);
  9231. }
  9232. }
  9233. if (!shader) {
  9234. throw new Error("Something went wrong while compile the shader.");
  9235. }
  9236. return shader;
  9237. };
  9238. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9239. var magFilter = gl.NEAREST;
  9240. var minFilter = gl.NEAREST;
  9241. switch (samplingMode) {
  9242. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9243. magFilter = gl.LINEAR;
  9244. if (generateMipMaps) {
  9245. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9246. }
  9247. else {
  9248. minFilter = gl.LINEAR;
  9249. }
  9250. break;
  9251. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9252. magFilter = gl.LINEAR;
  9253. if (generateMipMaps) {
  9254. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9255. }
  9256. else {
  9257. minFilter = gl.LINEAR;
  9258. }
  9259. break;
  9260. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9261. magFilter = gl.NEAREST;
  9262. if (generateMipMaps) {
  9263. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9264. }
  9265. else {
  9266. minFilter = gl.NEAREST;
  9267. }
  9268. break;
  9269. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9270. magFilter = gl.NEAREST;
  9271. if (generateMipMaps) {
  9272. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9273. }
  9274. else {
  9275. minFilter = gl.NEAREST;
  9276. }
  9277. break;
  9278. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9279. magFilter = gl.NEAREST;
  9280. if (generateMipMaps) {
  9281. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9282. }
  9283. else {
  9284. minFilter = gl.LINEAR;
  9285. }
  9286. break;
  9287. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9288. magFilter = gl.NEAREST;
  9289. if (generateMipMaps) {
  9290. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9291. }
  9292. else {
  9293. minFilter = gl.LINEAR;
  9294. }
  9295. break;
  9296. case BABYLON.Texture.NEAREST_LINEAR:
  9297. magFilter = gl.NEAREST;
  9298. minFilter = gl.LINEAR;
  9299. break;
  9300. case BABYLON.Texture.NEAREST_NEAREST:
  9301. magFilter = gl.NEAREST;
  9302. minFilter = gl.NEAREST;
  9303. break;
  9304. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9305. magFilter = gl.LINEAR;
  9306. if (generateMipMaps) {
  9307. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9308. }
  9309. else {
  9310. minFilter = gl.NEAREST;
  9311. }
  9312. break;
  9313. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9314. magFilter = gl.LINEAR;
  9315. if (generateMipMaps) {
  9316. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9317. }
  9318. else {
  9319. minFilter = gl.NEAREST;
  9320. }
  9321. break;
  9322. case BABYLON.Texture.LINEAR_LINEAR:
  9323. magFilter = gl.LINEAR;
  9324. minFilter = gl.LINEAR;
  9325. break;
  9326. case BABYLON.Texture.LINEAR_NEAREST:
  9327. magFilter = gl.LINEAR;
  9328. minFilter = gl.NEAREST;
  9329. break;
  9330. }
  9331. return {
  9332. min: minFilter,
  9333. mag: magFilter
  9334. };
  9335. };
  9336. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9337. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9338. var img;
  9339. var onload = function () {
  9340. loadedImages[index] = img;
  9341. loadedImages._internalCount++;
  9342. if (scene) {
  9343. scene._removePendingData(img);
  9344. }
  9345. if (loadedImages._internalCount === 6) {
  9346. onfinish(loadedImages);
  9347. }
  9348. };
  9349. var onerror = function (message, exception) {
  9350. if (scene) {
  9351. scene._removePendingData(img);
  9352. }
  9353. if (onErrorCallBack) {
  9354. onErrorCallBack(message, exception);
  9355. }
  9356. };
  9357. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9358. if (scene) {
  9359. scene._addPendingData(img);
  9360. }
  9361. };
  9362. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9363. if (onError === void 0) { onError = null; }
  9364. var loadedImages = [];
  9365. loadedImages._internalCount = 0;
  9366. for (var index = 0; index < 6; index++) {
  9367. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9368. }
  9369. };
  9370. var BufferPointer = /** @class */ (function () {
  9371. function BufferPointer() {
  9372. }
  9373. return BufferPointer;
  9374. }());
  9375. var InstancingAttributeInfo = /** @class */ (function () {
  9376. function InstancingAttributeInfo() {
  9377. }
  9378. return InstancingAttributeInfo;
  9379. }());
  9380. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9381. /**
  9382. * Define options used to create a render target texture
  9383. */
  9384. var RenderTargetCreationOptions = /** @class */ (function () {
  9385. function RenderTargetCreationOptions() {
  9386. }
  9387. return RenderTargetCreationOptions;
  9388. }());
  9389. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9390. /**
  9391. * Regroup several parameters relative to the browser in use
  9392. */
  9393. var EngineCapabilities = /** @class */ (function () {
  9394. function EngineCapabilities() {
  9395. }
  9396. return EngineCapabilities;
  9397. }());
  9398. BABYLON.EngineCapabilities = EngineCapabilities;
  9399. /**
  9400. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9401. */
  9402. var Engine = /** @class */ (function () {
  9403. /**
  9404. * @constructor
  9405. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9406. * @param antialias defines enable antialiasing (default: false)
  9407. * @param options defines further options to be sent to the getContext() function
  9408. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9409. */
  9410. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9411. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9412. var _this = this;
  9413. // Public members
  9414. this.forcePOTTextures = false;
  9415. this.isFullscreen = false;
  9416. this.isPointerLock = false;
  9417. this.cullBackFaces = true;
  9418. this.renderEvenInBackground = true;
  9419. this.preventCacheWipeBetweenFrames = false;
  9420. // To enable/disable IDB support and avoid XHR on .manifest
  9421. this.enableOfflineSupport = false;
  9422. this.scenes = new Array();
  9423. this.postProcesses = new Array();
  9424. // Observables
  9425. /**
  9426. * Observable event triggered each time the rendering canvas is resized
  9427. */
  9428. this.onResizeObservable = new BABYLON.Observable();
  9429. /**
  9430. * Observable event triggered each time the canvas loses focus
  9431. */
  9432. this.onCanvasBlurObservable = new BABYLON.Observable();
  9433. /**
  9434. * Observable event triggered each time the canvas gains focus
  9435. */
  9436. this.onCanvasFocusObservable = new BABYLON.Observable();
  9437. /**
  9438. * Observable event triggered each time the canvas receives pointerout event
  9439. */
  9440. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9441. /**
  9442. * Observable event triggered before each texture is initialized
  9443. */
  9444. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9445. //WebVR
  9446. this._vrDisplay = undefined;
  9447. this._vrSupported = false;
  9448. this._vrExclusivePointerMode = false;
  9449. // Uniform buffers list
  9450. this.disableUniformBuffers = false;
  9451. this._uniformBuffers = new Array();
  9452. // Observables
  9453. /**
  9454. * Observable raised when the engine begins a new frame
  9455. */
  9456. this.onBeginFrameObservable = new BABYLON.Observable();
  9457. /**
  9458. * Observable raised when the engine ends the current frame
  9459. */
  9460. this.onEndFrameObservable = new BABYLON.Observable();
  9461. /**
  9462. * Observable raised when the engine is about to compile a shader
  9463. */
  9464. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9465. /**
  9466. * Observable raised when the engine has jsut compiled a shader
  9467. */
  9468. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9469. this._windowIsBackground = false;
  9470. this._webGLVersion = 1.0;
  9471. this._badOS = false;
  9472. this._badDesktopOS = false;
  9473. /**
  9474. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9475. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9476. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9477. */
  9478. this.disableTextureBindingOptimization = false;
  9479. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9480. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9481. this.onVRRequestPresentStart = new BABYLON.Observable();
  9482. this._colorWrite = true;
  9483. this._drawCalls = new BABYLON.PerfCounter();
  9484. this._textureCollisions = new BABYLON.PerfCounter();
  9485. this._renderingQueueLaunched = false;
  9486. this._activeRenderLoops = new Array();
  9487. // Deterministic lockstepMaxSteps
  9488. this._deterministicLockstep = false;
  9489. this._lockstepMaxSteps = 4;
  9490. // Lost context
  9491. this.onContextLostObservable = new BABYLON.Observable();
  9492. this.onContextRestoredObservable = new BABYLON.Observable();
  9493. this._contextWasLost = false;
  9494. this._doNotHandleContextLost = false;
  9495. // FPS
  9496. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9497. this._fps = 60;
  9498. this._deltaTime = 0;
  9499. /**
  9500. * Turn this value on if you want to pause FPS computation when in background
  9501. */
  9502. this.disablePerformanceMonitorInBackground = false;
  9503. // States
  9504. this._depthCullingState = new BABYLON._DepthCullingState();
  9505. this._stencilState = new BABYLON._StencilState();
  9506. this._alphaState = new BABYLON._AlphaState();
  9507. this._alphaMode = Engine.ALPHA_DISABLE;
  9508. // Cache
  9509. this._internalTexturesCache = new Array();
  9510. this._activeChannel = 0;
  9511. this._currentTextureChannel = -1;
  9512. this._boundTexturesCache = {};
  9513. this._compiledEffects = {};
  9514. this._vertexAttribArraysEnabled = [];
  9515. this._uintIndicesCurrentlySet = false;
  9516. this._currentBoundBuffer = new Array();
  9517. this._currentBufferPointers = new Array();
  9518. this._currentInstanceLocations = new Array();
  9519. this._currentInstanceBuffers = new Array();
  9520. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9521. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9522. this._vaoRecordInProgress = false;
  9523. this._mustWipeVertexAttributes = false;
  9524. this._nextFreeTextureSlots = new Array();
  9525. this._maxSimultaneousTextures = 0;
  9526. this._activeRequests = new Array();
  9527. // Hardware supported Compressed Textures
  9528. this._texturesSupported = new Array();
  9529. this._onVRFullScreenTriggered = function () {
  9530. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9531. //get the old size before we change
  9532. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9533. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9534. //get the width and height, change the render size
  9535. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9536. _this.setHardwareScalingLevel(1);
  9537. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9538. }
  9539. else {
  9540. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9541. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9542. }
  9543. };
  9544. this._boundUniforms = {};
  9545. // Register promises
  9546. BABYLON.PromisePolyfill.Apply();
  9547. var canvas = null;
  9548. Engine.Instances.push(this);
  9549. if (!canvasOrContext) {
  9550. return;
  9551. }
  9552. options = options || {};
  9553. if (canvasOrContext.getContext) {
  9554. canvas = canvasOrContext;
  9555. this._renderingCanvas = canvas;
  9556. if (antialias != null) {
  9557. options.antialias = antialias;
  9558. }
  9559. if (options.deterministicLockstep === undefined) {
  9560. options.deterministicLockstep = false;
  9561. }
  9562. if (options.lockstepMaxSteps === undefined) {
  9563. options.lockstepMaxSteps = 4;
  9564. }
  9565. if (options.preserveDrawingBuffer === undefined) {
  9566. options.preserveDrawingBuffer = false;
  9567. }
  9568. if (options.audioEngine === undefined) {
  9569. options.audioEngine = true;
  9570. }
  9571. if (options.stencil === undefined) {
  9572. options.stencil = true;
  9573. }
  9574. this._deterministicLockstep = options.deterministicLockstep;
  9575. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9576. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9577. // Exceptions
  9578. if (navigator && navigator.userAgent) {
  9579. var ua = navigator.userAgent;
  9580. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9581. var exception = _a[_i];
  9582. var key = exception.key;
  9583. var targets = exception.targets;
  9584. if (ua.indexOf(key) > -1) {
  9585. if (exception.capture && exception.captureConstraint) {
  9586. var capture = exception.capture;
  9587. var constraint = exception.captureConstraint;
  9588. var regex = new RegExp(capture);
  9589. var matches = regex.exec(ua);
  9590. if (matches && matches.length > 0) {
  9591. var capturedValue = parseInt(matches[matches.length - 1]);
  9592. if (capturedValue >= constraint) {
  9593. continue;
  9594. }
  9595. }
  9596. }
  9597. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9598. var target = targets_1[_b];
  9599. switch (target) {
  9600. case "uniformBuffer":
  9601. this.disableUniformBuffers = true;
  9602. break;
  9603. case "textureBindingOptimization":
  9604. this.disableTextureBindingOptimization = true;
  9605. break;
  9606. }
  9607. }
  9608. break;
  9609. }
  9610. }
  9611. }
  9612. // GL
  9613. if (!options.disableWebGL2Support) {
  9614. try {
  9615. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9616. if (this._gl) {
  9617. this._webGLVersion = 2.0;
  9618. }
  9619. }
  9620. catch (e) {
  9621. // Do nothing
  9622. }
  9623. }
  9624. if (!this._gl) {
  9625. if (!canvas) {
  9626. throw new Error("The provided canvas is null or undefined.");
  9627. }
  9628. try {
  9629. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9630. }
  9631. catch (e) {
  9632. throw new Error("WebGL not supported");
  9633. }
  9634. }
  9635. if (!this._gl) {
  9636. throw new Error("WebGL not supported");
  9637. }
  9638. this._onCanvasFocus = function () {
  9639. _this.onCanvasFocusObservable.notifyObservers(_this);
  9640. };
  9641. this._onCanvasBlur = function () {
  9642. _this.onCanvasBlurObservable.notifyObservers(_this);
  9643. };
  9644. canvas.addEventListener("focus", this._onCanvasFocus);
  9645. canvas.addEventListener("blur", this._onCanvasBlur);
  9646. this._onBlur = function () {
  9647. if (_this.disablePerformanceMonitorInBackground) {
  9648. _this._performanceMonitor.disable();
  9649. }
  9650. _this._windowIsBackground = true;
  9651. };
  9652. this._onFocus = function () {
  9653. if (_this.disablePerformanceMonitorInBackground) {
  9654. _this._performanceMonitor.enable();
  9655. }
  9656. _this._windowIsBackground = false;
  9657. };
  9658. this._onCanvasPointerOut = function () {
  9659. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9660. };
  9661. window.addEventListener("blur", this._onBlur);
  9662. window.addEventListener("focus", this._onFocus);
  9663. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9664. // Context lost
  9665. if (!this._doNotHandleContextLost) {
  9666. this._onContextLost = function (evt) {
  9667. evt.preventDefault();
  9668. _this._contextWasLost = true;
  9669. BABYLON.Tools.Warn("WebGL context lost.");
  9670. _this.onContextLostObservable.notifyObservers(_this);
  9671. };
  9672. this._onContextRestored = function (evt) {
  9673. // Adding a timeout to avoid race condition at browser level
  9674. setTimeout(function () {
  9675. // Rebuild gl context
  9676. _this._initGLContext();
  9677. // Rebuild effects
  9678. _this._rebuildEffects();
  9679. // Rebuild textures
  9680. _this._rebuildInternalTextures();
  9681. // Rebuild buffers
  9682. _this._rebuildBuffers();
  9683. // Cache
  9684. _this.wipeCaches(true);
  9685. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9686. _this.onContextRestoredObservable.notifyObservers(_this);
  9687. _this._contextWasLost = false;
  9688. }, 0);
  9689. };
  9690. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9691. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9692. }
  9693. }
  9694. else {
  9695. this._gl = canvasOrContext;
  9696. this._renderingCanvas = this._gl.canvas;
  9697. if (this._gl.renderbufferStorageMultisample) {
  9698. this._webGLVersion = 2.0;
  9699. }
  9700. options.stencil = this._gl.getContextAttributes().stencil;
  9701. }
  9702. // Viewport
  9703. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9704. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9705. this.resize();
  9706. this._isStencilEnable = options.stencil ? true : false;
  9707. this._initGLContext();
  9708. if (canvas) {
  9709. // Fullscreen
  9710. this._onFullscreenChange = function () {
  9711. if (document.fullscreen !== undefined) {
  9712. _this.isFullscreen = document.fullscreen;
  9713. }
  9714. else if (document.mozFullScreen !== undefined) {
  9715. _this.isFullscreen = document.mozFullScreen;
  9716. }
  9717. else if (document.webkitIsFullScreen !== undefined) {
  9718. _this.isFullscreen = document.webkitIsFullScreen;
  9719. }
  9720. else if (document.msIsFullScreen !== undefined) {
  9721. _this.isFullscreen = document.msIsFullScreen;
  9722. }
  9723. // Pointer lock
  9724. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9725. canvas.requestPointerLock = canvas.requestPointerLock ||
  9726. canvas.msRequestPointerLock ||
  9727. canvas.mozRequestPointerLock ||
  9728. canvas.webkitRequestPointerLock;
  9729. if (canvas.requestPointerLock) {
  9730. canvas.requestPointerLock();
  9731. }
  9732. }
  9733. };
  9734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9738. // Pointer lock
  9739. this._onPointerLockChange = function () {
  9740. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9741. document.webkitPointerLockElement === canvas ||
  9742. document.msPointerLockElement === canvas ||
  9743. document.pointerLockElement === canvas);
  9744. };
  9745. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9746. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9747. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9748. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9749. this._onVRDisplayPointerRestricted = function () {
  9750. if (canvas) {
  9751. canvas.requestPointerLock();
  9752. }
  9753. };
  9754. this._onVRDisplayPointerUnrestricted = function () {
  9755. document.exitPointerLock();
  9756. };
  9757. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9758. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9759. }
  9760. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9761. Engine.audioEngine = new BABYLON.AudioEngine();
  9762. }
  9763. // Prepare buffer pointers
  9764. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9765. this._currentBufferPointers[i] = new BufferPointer();
  9766. }
  9767. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9768. // Load WebVR Devices
  9769. if (options.autoEnableWebVR) {
  9770. this.initWebVR();
  9771. }
  9772. // Detect if we are running on a faulty buggy OS.
  9773. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9774. // Detect if we are running on a faulty buggy desktop OS.
  9775. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9776. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9777. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9778. }
  9779. Object.defineProperty(Engine, "LastCreatedEngine", {
  9780. get: function () {
  9781. if (Engine.Instances.length === 0) {
  9782. return null;
  9783. }
  9784. return Engine.Instances[Engine.Instances.length - 1];
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Object.defineProperty(Engine, "LastCreatedScene", {
  9790. get: function () {
  9791. var lastCreatedEngine = Engine.LastCreatedEngine;
  9792. if (!lastCreatedEngine) {
  9793. return null;
  9794. }
  9795. if (lastCreatedEngine.scenes.length === 0) {
  9796. return null;
  9797. }
  9798. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. /**
  9804. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9805. */
  9806. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9807. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9808. var engine = Engine.Instances[engineIndex];
  9809. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9810. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9811. }
  9812. }
  9813. };
  9814. Object.defineProperty(Engine, "NEVER", {
  9815. get: function () {
  9816. return Engine._NEVER;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(Engine, "ALWAYS", {
  9822. get: function () {
  9823. return Engine._ALWAYS;
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(Engine, "LESS", {
  9829. get: function () {
  9830. return Engine._LESS;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(Engine, "EQUAL", {
  9836. get: function () {
  9837. return Engine._EQUAL;
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(Engine, "LEQUAL", {
  9843. get: function () {
  9844. return Engine._LEQUAL;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(Engine, "GREATER", {
  9850. get: function () {
  9851. return Engine._GREATER;
  9852. },
  9853. enumerable: true,
  9854. configurable: true
  9855. });
  9856. Object.defineProperty(Engine, "GEQUAL", {
  9857. get: function () {
  9858. return Engine._GEQUAL;
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(Engine, "NOTEQUAL", {
  9864. get: function () {
  9865. return Engine._NOTEQUAL;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Object.defineProperty(Engine, "KEEP", {
  9871. get: function () {
  9872. return Engine._KEEP;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Engine, "REPLACE", {
  9878. get: function () {
  9879. return Engine._REPLACE;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Engine, "INCR", {
  9885. get: function () {
  9886. return Engine._INCR;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Engine, "DECR", {
  9892. get: function () {
  9893. return Engine._DECR;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(Engine, "INVERT", {
  9899. get: function () {
  9900. return Engine._INVERT;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Engine, "INCR_WRAP", {
  9906. get: function () {
  9907. return Engine._INCR_WRAP;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(Engine, "DECR_WRAP", {
  9913. get: function () {
  9914. return Engine._DECR_WRAP;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9920. get: function () {
  9921. return Engine._ALPHA_DISABLE;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9927. get: function () {
  9928. return Engine._ALPHA_ONEONE;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(Engine, "ALPHA_ADD", {
  9934. get: function () {
  9935. return Engine._ALPHA_ADD;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9941. get: function () {
  9942. return Engine._ALPHA_COMBINE;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9948. get: function () {
  9949. return Engine._ALPHA_SUBTRACT;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9955. get: function () {
  9956. return Engine._ALPHA_MULTIPLY;
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9962. get: function () {
  9963. return Engine._ALPHA_MAXIMIZED;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9969. get: function () {
  9970. return Engine._ALPHA_PREMULTIPLIED;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9976. get: function () {
  9977. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9983. get: function () {
  9984. return Engine._ALPHA_INTERPOLATE;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9990. get: function () {
  9991. return Engine._ALPHA_SCREENMODE;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9997. get: function () {
  9998. return Engine._DELAYLOADSTATE_NONE;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10004. get: function () {
  10005. return Engine._DELAYLOADSTATE_LOADED;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10011. get: function () {
  10012. return Engine._DELAYLOADSTATE_LOADING;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10018. get: function () {
  10019. return Engine._DELAYLOADSTATE_NOTLOADED;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10025. get: function () {
  10026. return Engine._TEXTUREFORMAT_ALPHA;
  10027. },
  10028. enumerable: true,
  10029. configurable: true
  10030. });
  10031. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10032. get: function () {
  10033. return Engine._TEXTUREFORMAT_LUMINANCE;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10039. get: function () {
  10040. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10041. },
  10042. enumerable: true,
  10043. configurable: true
  10044. });
  10045. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10046. get: function () {
  10047. return Engine._TEXTUREFORMAT_RGB;
  10048. },
  10049. enumerable: true,
  10050. configurable: true
  10051. });
  10052. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10053. get: function () {
  10054. return Engine._TEXTUREFORMAT_RGBA;
  10055. },
  10056. enumerable: true,
  10057. configurable: true
  10058. });
  10059. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10060. get: function () {
  10061. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10067. get: function () {
  10068. return Engine._TEXTURETYPE_FLOAT;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10074. get: function () {
  10075. return Engine._TEXTURETYPE_HALF_FLOAT;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10081. get: function () {
  10082. return Engine._SCALEMODE_FLOOR;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10088. get: function () {
  10089. return Engine._SCALEMODE_NEAREST;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10095. get: function () {
  10096. return Engine._SCALEMODE_CEILING;
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Object.defineProperty(Engine, "Version", {
  10102. get: function () {
  10103. return "3.2.0-alpha6";
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10109. get: function () {
  10110. return this._vrExclusivePointerMode;
  10111. },
  10112. enumerable: true,
  10113. configurable: true
  10114. });
  10115. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10116. get: function () {
  10117. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10123. get: function () {
  10124. return this._webGLVersion < 2 || this.forcePOTTextures;
  10125. },
  10126. enumerable: true,
  10127. configurable: true
  10128. });
  10129. Object.defineProperty(Engine.prototype, "badOS", {
  10130. get: function () {
  10131. return this._badOS;
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10137. get: function () {
  10138. return this._badDesktopOS;
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10144. get: function () {
  10145. return this._performanceMonitor;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10151. get: function () {
  10152. return this._texturesSupported;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10158. get: function () {
  10159. return this._textureFormatInUse;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(Engine.prototype, "currentViewport", {
  10165. get: function () {
  10166. return this._cachedViewport;
  10167. },
  10168. enumerable: true,
  10169. configurable: true
  10170. });
  10171. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10172. // Empty texture
  10173. get: function () {
  10174. if (!this._emptyTexture) {
  10175. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10176. }
  10177. return this._emptyTexture;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10183. get: function () {
  10184. if (!this._emptyTexture3D) {
  10185. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10186. }
  10187. return this._emptyTexture3D;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10193. get: function () {
  10194. if (!this._emptyCubeTexture) {
  10195. var faceData = new Uint8Array(4);
  10196. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10197. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10198. }
  10199. return this._emptyCubeTexture;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Engine.prototype._rebuildInternalTextures = function () {
  10205. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10206. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10207. var internalTexture = currentState_1[_i];
  10208. internalTexture._rebuild();
  10209. }
  10210. };
  10211. Engine.prototype._rebuildEffects = function () {
  10212. for (var key in this._compiledEffects) {
  10213. var effect = this._compiledEffects[key];
  10214. effect._prepareEffect();
  10215. }
  10216. BABYLON.Effect.ResetCache();
  10217. };
  10218. Engine.prototype._rebuildBuffers = function () {
  10219. // Index / Vertex
  10220. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10221. var scene = _a[_i];
  10222. scene.resetCachedMaterial();
  10223. scene._rebuildGeometries();
  10224. scene._rebuildTextures();
  10225. }
  10226. // Uniforms
  10227. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10228. var uniformBuffer = _c[_b];
  10229. uniformBuffer._rebuild();
  10230. }
  10231. };
  10232. Engine.prototype._initGLContext = function () {
  10233. // Caps
  10234. this._caps = new EngineCapabilities();
  10235. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10236. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10237. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10238. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10239. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10240. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10241. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10242. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10243. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10244. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10245. // Infos
  10246. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10247. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10248. if (rendererInfo != null) {
  10249. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10250. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10251. }
  10252. if (!this._glVendor) {
  10253. this._glVendor = "Unknown vendor";
  10254. }
  10255. if (!this._glRenderer) {
  10256. this._glRenderer = "Unknown renderer";
  10257. }
  10258. // Constants
  10259. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10260. if (this._gl.RGBA16F !== 0x881A) {
  10261. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10262. }
  10263. if (this._gl.RGBA32F !== 0x8814) {
  10264. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10265. }
  10266. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10267. this._gl.DEPTH24_STENCIL8 = 35056;
  10268. }
  10269. // Extensions
  10270. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10271. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10272. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10273. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10274. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10275. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10276. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10277. 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');
  10278. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10279. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10280. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10281. this._caps.highPrecisionShaderSupported = true;
  10282. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10283. if (this._caps.timerQuery) {
  10284. if (this._webGLVersion === 1) {
  10285. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10286. }
  10287. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10288. }
  10289. // Checks if some of the format renders first to allow the use of webgl inspector.
  10290. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10291. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10292. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10293. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10294. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10295. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10296. if (this._webGLVersion > 1) {
  10297. this._gl.HALF_FLOAT_OES = 0x140B;
  10298. }
  10299. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10300. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10301. // Draw buffers
  10302. if (this._webGLVersion > 1) {
  10303. this._caps.drawBuffersExtension = true;
  10304. }
  10305. else {
  10306. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10307. if (drawBuffersExtension !== null) {
  10308. this._caps.drawBuffersExtension = true;
  10309. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10310. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10311. for (var i = 0; i < 16; i++) {
  10312. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10313. }
  10314. }
  10315. else {
  10316. this._caps.drawBuffersExtension = false;
  10317. }
  10318. }
  10319. // Depth Texture
  10320. if (this._webGLVersion > 1) {
  10321. this._caps.depthTextureExtension = true;
  10322. }
  10323. else {
  10324. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10325. if (depthTextureExtension != null) {
  10326. this._caps.depthTextureExtension = true;
  10327. }
  10328. }
  10329. // Vertex array object
  10330. if (this._webGLVersion > 1) {
  10331. this._caps.vertexArrayObject = true;
  10332. }
  10333. else {
  10334. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10335. if (vertexArrayObjectExtension != null) {
  10336. this._caps.vertexArrayObject = true;
  10337. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10338. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10339. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10340. }
  10341. else {
  10342. this._caps.vertexArrayObject = false;
  10343. }
  10344. }
  10345. // Instances count
  10346. if (this._webGLVersion > 1) {
  10347. this._caps.instancedArrays = true;
  10348. }
  10349. else {
  10350. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10351. if (instanceExtension != null) {
  10352. this._caps.instancedArrays = true;
  10353. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10354. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10355. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10356. }
  10357. else {
  10358. this._caps.instancedArrays = false;
  10359. }
  10360. }
  10361. // Intelligently add supported compressed formats in order to check for.
  10362. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10363. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10364. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10365. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10366. if (this._caps.astc)
  10367. this.texturesSupported.push('-astc.ktx');
  10368. if (this._caps.s3tc)
  10369. this.texturesSupported.push('-dxt.ktx');
  10370. if (this._caps.pvrtc)
  10371. this.texturesSupported.push('-pvrtc.ktx');
  10372. if (this._caps.etc2)
  10373. this.texturesSupported.push('-etc2.ktx');
  10374. if (this._caps.etc1)
  10375. this.texturesSupported.push('-etc1.ktx');
  10376. if (this._gl.getShaderPrecisionFormat) {
  10377. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10378. if (highp) {
  10379. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10380. }
  10381. }
  10382. // Depth buffer
  10383. this.setDepthBuffer(true);
  10384. this.setDepthFunctionToLessOrEqual();
  10385. this.setDepthWrite(true);
  10386. // Texture maps
  10387. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10388. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10389. this._nextFreeTextureSlots.push(slot);
  10390. }
  10391. };
  10392. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10393. get: function () {
  10394. return this._webGLVersion;
  10395. },
  10396. enumerable: true,
  10397. configurable: true
  10398. });
  10399. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10400. /**
  10401. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10402. */
  10403. get: function () {
  10404. return this._isStencilEnable;
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Engine.prototype._prepareWorkingCanvas = function () {
  10410. if (this._workingCanvas) {
  10411. return;
  10412. }
  10413. this._workingCanvas = document.createElement("canvas");
  10414. var context = this._workingCanvas.getContext("2d");
  10415. if (context) {
  10416. this._workingContext = context;
  10417. }
  10418. };
  10419. Engine.prototype.resetTextureCache = function () {
  10420. for (var key in this._boundTexturesCache) {
  10421. var boundTexture = this._boundTexturesCache[key];
  10422. if (boundTexture) {
  10423. this._removeDesignatedSlot(boundTexture);
  10424. }
  10425. this._boundTexturesCache[key] = null;
  10426. }
  10427. if (!this.disableTextureBindingOptimization) {
  10428. this._nextFreeTextureSlots = [];
  10429. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10430. this._nextFreeTextureSlots.push(slot);
  10431. }
  10432. }
  10433. this._currentTextureChannel = -1;
  10434. };
  10435. Engine.prototype.isDeterministicLockStep = function () {
  10436. return this._deterministicLockstep;
  10437. };
  10438. Engine.prototype.getLockstepMaxSteps = function () {
  10439. return this._lockstepMaxSteps;
  10440. };
  10441. Engine.prototype.getGlInfo = function () {
  10442. return {
  10443. vendor: this._glVendor,
  10444. renderer: this._glRenderer,
  10445. version: this._glVersion
  10446. };
  10447. };
  10448. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10449. if (useScreen === void 0) { useScreen = false; }
  10450. var viewport = camera.viewport;
  10451. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10452. };
  10453. Engine.prototype.getRenderWidth = function (useScreen) {
  10454. if (useScreen === void 0) { useScreen = false; }
  10455. if (!useScreen && this._currentRenderTarget) {
  10456. return this._currentRenderTarget.width;
  10457. }
  10458. return this._gl.drawingBufferWidth;
  10459. };
  10460. Engine.prototype.getRenderHeight = function (useScreen) {
  10461. if (useScreen === void 0) { useScreen = false; }
  10462. if (!useScreen && this._currentRenderTarget) {
  10463. return this._currentRenderTarget.height;
  10464. }
  10465. return this._gl.drawingBufferHeight;
  10466. };
  10467. Engine.prototype.getRenderingCanvas = function () {
  10468. return this._renderingCanvas;
  10469. };
  10470. Engine.prototype.getRenderingCanvasClientRect = function () {
  10471. if (!this._renderingCanvas) {
  10472. return null;
  10473. }
  10474. return this._renderingCanvas.getBoundingClientRect();
  10475. };
  10476. Engine.prototype.setHardwareScalingLevel = function (level) {
  10477. this._hardwareScalingLevel = level;
  10478. this.resize();
  10479. };
  10480. Engine.prototype.getHardwareScalingLevel = function () {
  10481. return this._hardwareScalingLevel;
  10482. };
  10483. Engine.prototype.getLoadedTexturesCache = function () {
  10484. return this._internalTexturesCache;
  10485. };
  10486. Engine.prototype.getCaps = function () {
  10487. return this._caps;
  10488. };
  10489. Object.defineProperty(Engine.prototype, "drawCalls", {
  10490. /** The number of draw calls submitted last frame */
  10491. get: function () {
  10492. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10493. return 0;
  10494. },
  10495. enumerable: true,
  10496. configurable: true
  10497. });
  10498. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10499. get: function () {
  10500. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10501. return null;
  10502. },
  10503. enumerable: true,
  10504. configurable: true
  10505. });
  10506. Engine.prototype.getDepthFunction = function () {
  10507. return this._depthCullingState.depthFunc;
  10508. };
  10509. Engine.prototype.setDepthFunction = function (depthFunc) {
  10510. this._depthCullingState.depthFunc = depthFunc;
  10511. };
  10512. Engine.prototype.setDepthFunctionToGreater = function () {
  10513. this._depthCullingState.depthFunc = this._gl.GREATER;
  10514. };
  10515. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10516. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10517. };
  10518. Engine.prototype.setDepthFunctionToLess = function () {
  10519. this._depthCullingState.depthFunc = this._gl.LESS;
  10520. };
  10521. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10522. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10523. };
  10524. Engine.prototype.getStencilBuffer = function () {
  10525. return this._stencilState.stencilTest;
  10526. };
  10527. Engine.prototype.setStencilBuffer = function (enable) {
  10528. this._stencilState.stencilTest = enable;
  10529. };
  10530. Engine.prototype.getStencilMask = function () {
  10531. return this._stencilState.stencilMask;
  10532. };
  10533. Engine.prototype.setStencilMask = function (mask) {
  10534. this._stencilState.stencilMask = mask;
  10535. };
  10536. Engine.prototype.getStencilFunction = function () {
  10537. return this._stencilState.stencilFunc;
  10538. };
  10539. Engine.prototype.getStencilFunctionReference = function () {
  10540. return this._stencilState.stencilFuncRef;
  10541. };
  10542. Engine.prototype.getStencilFunctionMask = function () {
  10543. return this._stencilState.stencilFuncMask;
  10544. };
  10545. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10546. this._stencilState.stencilFunc = stencilFunc;
  10547. };
  10548. Engine.prototype.setStencilFunctionReference = function (reference) {
  10549. this._stencilState.stencilFuncRef = reference;
  10550. };
  10551. Engine.prototype.setStencilFunctionMask = function (mask) {
  10552. this._stencilState.stencilFuncMask = mask;
  10553. };
  10554. Engine.prototype.getStencilOperationFail = function () {
  10555. return this._stencilState.stencilOpStencilFail;
  10556. };
  10557. Engine.prototype.getStencilOperationDepthFail = function () {
  10558. return this._stencilState.stencilOpDepthFail;
  10559. };
  10560. Engine.prototype.getStencilOperationPass = function () {
  10561. return this._stencilState.stencilOpStencilDepthPass;
  10562. };
  10563. Engine.prototype.setStencilOperationFail = function (operation) {
  10564. this._stencilState.stencilOpStencilFail = operation;
  10565. };
  10566. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10567. this._stencilState.stencilOpDepthFail = operation;
  10568. };
  10569. Engine.prototype.setStencilOperationPass = function (operation) {
  10570. this._stencilState.stencilOpStencilDepthPass = operation;
  10571. };
  10572. Engine.prototype.setDitheringState = function (value) {
  10573. if (value) {
  10574. this._gl.enable(this._gl.DITHER);
  10575. }
  10576. else {
  10577. this._gl.disable(this._gl.DITHER);
  10578. }
  10579. };
  10580. Engine.prototype.setRasterizerState = function (value) {
  10581. if (value) {
  10582. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10583. }
  10584. else {
  10585. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10586. }
  10587. };
  10588. /**
  10589. * stop executing a render loop function and remove it from the execution array
  10590. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10591. */
  10592. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10593. if (!renderFunction) {
  10594. this._activeRenderLoops = [];
  10595. return;
  10596. }
  10597. var index = this._activeRenderLoops.indexOf(renderFunction);
  10598. if (index >= 0) {
  10599. this._activeRenderLoops.splice(index, 1);
  10600. }
  10601. };
  10602. Engine.prototype._renderLoop = function () {
  10603. if (!this._contextWasLost) {
  10604. var shouldRender = true;
  10605. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10606. shouldRender = false;
  10607. }
  10608. if (shouldRender) {
  10609. // Start new frame
  10610. this.beginFrame();
  10611. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10612. var renderFunction = this._activeRenderLoops[index];
  10613. renderFunction();
  10614. }
  10615. // Present
  10616. this.endFrame();
  10617. }
  10618. }
  10619. if (this._activeRenderLoops.length > 0) {
  10620. // Register new frame
  10621. var requester = null;
  10622. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10623. requester = this._vrDisplay;
  10624. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10625. }
  10626. else {
  10627. this._renderingQueueLaunched = false;
  10628. }
  10629. };
  10630. /**
  10631. * Register and execute a render loop. The engine can have more than one render function.
  10632. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10633. * @example
  10634. * engine.runRenderLoop(function () {
  10635. * scene.render()
  10636. * })
  10637. */
  10638. Engine.prototype.runRenderLoop = function (renderFunction) {
  10639. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10640. return;
  10641. }
  10642. this._activeRenderLoops.push(renderFunction);
  10643. if (!this._renderingQueueLaunched) {
  10644. this._renderingQueueLaunched = true;
  10645. this._bindedRenderFunction = this._renderLoop.bind(this);
  10646. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10647. }
  10648. };
  10649. /**
  10650. * Toggle full screen mode.
  10651. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10652. * @param {any} options - an options object to be sent to the requestFullscreen function
  10653. */
  10654. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10655. if (this.isFullscreen) {
  10656. BABYLON.Tools.ExitFullscreen();
  10657. }
  10658. else {
  10659. this._pointerLockRequested = requestPointerLock;
  10660. if (this._renderingCanvas) {
  10661. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10662. }
  10663. }
  10664. };
  10665. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10666. if (stencil === void 0) { stencil = false; }
  10667. this.applyStates();
  10668. var mode = 0;
  10669. if (backBuffer && color) {
  10670. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10671. mode |= this._gl.COLOR_BUFFER_BIT;
  10672. }
  10673. if (depth) {
  10674. this._gl.clearDepth(1.0);
  10675. mode |= this._gl.DEPTH_BUFFER_BIT;
  10676. }
  10677. if (stencil) {
  10678. this._gl.clearStencil(0);
  10679. mode |= this._gl.STENCIL_BUFFER_BIT;
  10680. }
  10681. this._gl.clear(mode);
  10682. };
  10683. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10684. var gl = this._gl;
  10685. // Save state
  10686. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10687. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10688. // Change state
  10689. gl.enable(gl.SCISSOR_TEST);
  10690. gl.scissor(x, y, width, height);
  10691. // Clear
  10692. this.clear(clearColor, true, true, true);
  10693. // Restore state
  10694. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10695. if (curScissor === true) {
  10696. gl.enable(gl.SCISSOR_TEST);
  10697. }
  10698. else {
  10699. gl.disable(gl.SCISSOR_TEST);
  10700. }
  10701. };
  10702. /**
  10703. * Set the WebGL's viewport
  10704. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10705. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10706. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10707. */
  10708. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10709. var width = requiredWidth || this.getRenderWidth();
  10710. var height = requiredHeight || this.getRenderHeight();
  10711. var x = viewport.x || 0;
  10712. var y = viewport.y || 0;
  10713. this._cachedViewport = viewport;
  10714. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10715. };
  10716. /**
  10717. * Directly set the WebGL Viewport
  10718. * The x, y, width & height are directly passed to the WebGL call
  10719. * @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.
  10720. */
  10721. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10722. var currentViewport = this._cachedViewport;
  10723. this._cachedViewport = null;
  10724. this._gl.viewport(x, y, width, height);
  10725. return currentViewport;
  10726. };
  10727. Engine.prototype.beginFrame = function () {
  10728. this.onBeginFrameObservable.notifyObservers(this);
  10729. this._measureFps();
  10730. };
  10731. Engine.prototype.endFrame = function () {
  10732. //force a flush in case we are using a bad OS.
  10733. if (this._badOS) {
  10734. this.flushFramebuffer();
  10735. }
  10736. //submit frame to the vr device, if enabled
  10737. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10738. // TODO: We should only submit the frame if we read frameData successfully.
  10739. this._vrDisplay.submitFrame();
  10740. }
  10741. this.onEndFrameObservable.notifyObservers(this);
  10742. };
  10743. /**
  10744. * resize the view according to the canvas' size.
  10745. * @example
  10746. * window.addEventListener("resize", function () {
  10747. * engine.resize();
  10748. * });
  10749. */
  10750. Engine.prototype.resize = function () {
  10751. // We're not resizing the size of the canvas while in VR mode & presenting
  10752. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10753. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10754. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10755. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10756. }
  10757. };
  10758. /**
  10759. * force a specific size of the canvas
  10760. * @param {number} width - the new canvas' width
  10761. * @param {number} height - the new canvas' height
  10762. */
  10763. Engine.prototype.setSize = function (width, height) {
  10764. if (!this._renderingCanvas) {
  10765. return;
  10766. }
  10767. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10768. return;
  10769. }
  10770. this._renderingCanvas.width = width;
  10771. this._renderingCanvas.height = height;
  10772. for (var index = 0; index < this.scenes.length; index++) {
  10773. var scene = this.scenes[index];
  10774. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10775. var cam = scene.cameras[camIndex];
  10776. cam._currentRenderId = 0;
  10777. }
  10778. }
  10779. if (this.onResizeObservable.hasObservers) {
  10780. this.onResizeObservable.notifyObservers(this);
  10781. }
  10782. };
  10783. // WebVR functions
  10784. Engine.prototype.isVRDevicePresent = function () {
  10785. return !!this._vrDisplay;
  10786. };
  10787. Engine.prototype.getVRDevice = function () {
  10788. return this._vrDisplay;
  10789. };
  10790. Engine.prototype.initWebVR = function () {
  10791. var _this = this;
  10792. var notifyObservers = function () {
  10793. var eventArgs = {
  10794. vrDisplay: _this._vrDisplay,
  10795. vrSupported: _this._vrSupported
  10796. };
  10797. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10798. };
  10799. if (!this._onVrDisplayConnect) {
  10800. this._onVrDisplayConnect = function (event) {
  10801. _this._vrDisplay = event.display;
  10802. notifyObservers();
  10803. };
  10804. this._onVrDisplayDisconnect = function () {
  10805. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10806. _this._vrDisplay = undefined;
  10807. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10808. notifyObservers();
  10809. };
  10810. this._onVrDisplayPresentChange = function () {
  10811. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10812. };
  10813. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10814. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10815. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10816. }
  10817. this._getVRDisplays(notifyObservers);
  10818. return this.onVRDisplayChangedObservable;
  10819. };
  10820. Engine.prototype.enableVR = function () {
  10821. var _this = this;
  10822. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10823. var onResolved = function () {
  10824. _this.onVRRequestPresentComplete.notifyObservers(true);
  10825. _this._onVRFullScreenTriggered();
  10826. };
  10827. var onRejected = function () {
  10828. _this.onVRRequestPresentComplete.notifyObservers(false);
  10829. };
  10830. this.onVRRequestPresentStart.notifyObservers(this);
  10831. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10832. }
  10833. };
  10834. Engine.prototype.disableVR = function () {
  10835. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10836. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10837. }
  10838. };
  10839. Engine.prototype._getVRDisplays = function (callback) {
  10840. var _this = this;
  10841. var getWebVRDevices = function (devices) {
  10842. _this._vrSupported = true;
  10843. // note that devices may actually be an empty array. This is fine;
  10844. // we expect this._vrDisplay to be undefined in this case.
  10845. return _this._vrDisplay = devices[0];
  10846. };
  10847. if (navigator.getVRDisplays) {
  10848. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10849. // TODO: System CANNOT support WebVR, despite API presence.
  10850. _this._vrSupported = false;
  10851. callback();
  10852. });
  10853. }
  10854. else {
  10855. // TODO: Browser does not support WebVR
  10856. this._vrDisplay = undefined;
  10857. this._vrSupported = false;
  10858. callback();
  10859. }
  10860. };
  10861. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10862. if (this._currentRenderTarget) {
  10863. this.unBindFramebuffer(this._currentRenderTarget);
  10864. }
  10865. this._currentRenderTarget = texture;
  10866. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10867. var gl = this._gl;
  10868. if (texture.isCube) {
  10869. if (faceIndex === undefined) {
  10870. faceIndex = 0;
  10871. }
  10872. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10873. }
  10874. if (this._cachedViewport && !forceFullscreenViewport) {
  10875. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10876. }
  10877. else {
  10878. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10879. }
  10880. this.wipeCaches();
  10881. };
  10882. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10883. if (this._currentFramebuffer !== framebuffer) {
  10884. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10885. this._currentFramebuffer = framebuffer;
  10886. }
  10887. };
  10888. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10889. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10890. this._currentRenderTarget = null;
  10891. // If MSAA, we need to bitblt back to main texture
  10892. var gl = this._gl;
  10893. if (texture._MSAAFramebuffer) {
  10894. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10895. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10896. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10897. }
  10898. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10899. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10900. gl.generateMipmap(gl.TEXTURE_2D);
  10901. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10902. }
  10903. if (onBeforeUnbind) {
  10904. if (texture._MSAAFramebuffer) {
  10905. // Bind the correct framebuffer
  10906. this.bindUnboundFramebuffer(texture._framebuffer);
  10907. }
  10908. onBeforeUnbind();
  10909. }
  10910. this.bindUnboundFramebuffer(null);
  10911. };
  10912. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10913. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10914. this._currentRenderTarget = null;
  10915. // If MSAA, we need to bitblt back to main texture
  10916. var gl = this._gl;
  10917. if (textures[0]._MSAAFramebuffer) {
  10918. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10919. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10920. var attachments = textures[0]._attachments;
  10921. if (!attachments) {
  10922. attachments = new Array(textures.length);
  10923. textures[0]._attachments = attachments;
  10924. }
  10925. for (var i = 0; i < textures.length; i++) {
  10926. var texture = textures[i];
  10927. for (var j = 0; j < attachments.length; j++) {
  10928. attachments[j] = gl.NONE;
  10929. }
  10930. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10931. gl.readBuffer(attachments[i]);
  10932. gl.drawBuffers(attachments);
  10933. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10934. }
  10935. for (var i = 0; i < attachments.length; i++) {
  10936. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10937. }
  10938. gl.drawBuffers(attachments);
  10939. }
  10940. for (var i = 0; i < textures.length; i++) {
  10941. var texture = textures[i];
  10942. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10943. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10944. gl.generateMipmap(gl.TEXTURE_2D);
  10945. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10946. }
  10947. }
  10948. if (onBeforeUnbind) {
  10949. if (textures[0]._MSAAFramebuffer) {
  10950. // Bind the correct framebuffer
  10951. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10952. }
  10953. onBeforeUnbind();
  10954. }
  10955. this.bindUnboundFramebuffer(null);
  10956. };
  10957. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10958. if (texture.generateMipMaps) {
  10959. var gl = this._gl;
  10960. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10961. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10962. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10963. }
  10964. };
  10965. Engine.prototype.flushFramebuffer = function () {
  10966. this._gl.flush();
  10967. };
  10968. Engine.prototype.restoreDefaultFramebuffer = function () {
  10969. if (this._currentRenderTarget) {
  10970. this.unBindFramebuffer(this._currentRenderTarget);
  10971. }
  10972. else {
  10973. this.bindUnboundFramebuffer(null);
  10974. }
  10975. if (this._cachedViewport) {
  10976. this.setViewport(this._cachedViewport);
  10977. }
  10978. this.wipeCaches();
  10979. };
  10980. // UBOs
  10981. Engine.prototype.createUniformBuffer = function (elements) {
  10982. var ubo = this._gl.createBuffer();
  10983. if (!ubo) {
  10984. throw new Error("Unable to create uniform buffer");
  10985. }
  10986. this.bindUniformBuffer(ubo);
  10987. if (elements instanceof Float32Array) {
  10988. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10989. }
  10990. else {
  10991. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10992. }
  10993. this.bindUniformBuffer(null);
  10994. ubo.references = 1;
  10995. return ubo;
  10996. };
  10997. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10998. var ubo = this._gl.createBuffer();
  10999. if (!ubo) {
  11000. throw new Error("Unable to create dynamic uniform buffer");
  11001. }
  11002. this.bindUniformBuffer(ubo);
  11003. if (elements instanceof Float32Array) {
  11004. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11005. }
  11006. else {
  11007. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11008. }
  11009. this.bindUniformBuffer(null);
  11010. ubo.references = 1;
  11011. return ubo;
  11012. };
  11013. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11014. this.bindUniformBuffer(uniformBuffer);
  11015. if (offset === undefined) {
  11016. offset = 0;
  11017. }
  11018. if (count === undefined) {
  11019. if (elements instanceof Float32Array) {
  11020. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11021. }
  11022. else {
  11023. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11024. }
  11025. }
  11026. else {
  11027. if (elements instanceof Float32Array) {
  11028. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11029. }
  11030. else {
  11031. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11032. }
  11033. }
  11034. this.bindUniformBuffer(null);
  11035. };
  11036. // VBOs
  11037. Engine.prototype._resetVertexBufferBinding = function () {
  11038. this.bindArrayBuffer(null);
  11039. this._cachedVertexBuffers = null;
  11040. };
  11041. Engine.prototype.createVertexBuffer = function (vertices) {
  11042. var vbo = this._gl.createBuffer();
  11043. if (!vbo) {
  11044. throw new Error("Unable to create vertex buffer");
  11045. }
  11046. this.bindArrayBuffer(vbo);
  11047. if (vertices instanceof Float32Array) {
  11048. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11049. }
  11050. else {
  11051. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11052. }
  11053. this._resetVertexBufferBinding();
  11054. vbo.references = 1;
  11055. return vbo;
  11056. };
  11057. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11058. var vbo = this._gl.createBuffer();
  11059. if (!vbo) {
  11060. throw new Error("Unable to create dynamic vertex buffer");
  11061. }
  11062. this.bindArrayBuffer(vbo);
  11063. if (vertices instanceof Float32Array) {
  11064. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11065. }
  11066. else {
  11067. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11068. }
  11069. this._resetVertexBufferBinding();
  11070. vbo.references = 1;
  11071. return vbo;
  11072. };
  11073. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11074. if (offset === void 0) { offset = 0; }
  11075. // Force cache update
  11076. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11077. this.bindIndexBuffer(indexBuffer);
  11078. var arrayBuffer;
  11079. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11080. arrayBuffer = indices;
  11081. }
  11082. else {
  11083. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11084. }
  11085. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11086. this._resetIndexBufferBinding();
  11087. };
  11088. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11089. this.bindArrayBuffer(vertexBuffer);
  11090. if (offset === undefined) {
  11091. offset = 0;
  11092. }
  11093. if (count === undefined) {
  11094. if (vertices instanceof Float32Array) {
  11095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11096. }
  11097. else {
  11098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11099. }
  11100. }
  11101. else {
  11102. if (vertices instanceof Float32Array) {
  11103. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11104. }
  11105. else {
  11106. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11107. }
  11108. }
  11109. this._resetVertexBufferBinding();
  11110. };
  11111. Engine.prototype._resetIndexBufferBinding = function () {
  11112. this.bindIndexBuffer(null);
  11113. this._cachedIndexBuffer = null;
  11114. };
  11115. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11116. var vbo = this._gl.createBuffer();
  11117. if (!vbo) {
  11118. throw new Error("Unable to create index buffer");
  11119. }
  11120. this.bindIndexBuffer(vbo);
  11121. // Check for 32 bits indices
  11122. var arrayBuffer;
  11123. var need32Bits = false;
  11124. if (indices instanceof Uint16Array) {
  11125. arrayBuffer = indices;
  11126. }
  11127. else {
  11128. //check 32 bit support
  11129. if (this._caps.uintIndices) {
  11130. if (indices instanceof Uint32Array) {
  11131. arrayBuffer = indices;
  11132. need32Bits = true;
  11133. }
  11134. else {
  11135. //number[] or Int32Array, check if 32 bit is necessary
  11136. for (var index = 0; index < indices.length; index++) {
  11137. if (indices[index] > 65535) {
  11138. need32Bits = true;
  11139. break;
  11140. }
  11141. }
  11142. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11143. }
  11144. }
  11145. else {
  11146. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11147. arrayBuffer = new Uint16Array(indices);
  11148. }
  11149. }
  11150. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11151. this._resetIndexBufferBinding();
  11152. vbo.references = 1;
  11153. vbo.is32Bits = need32Bits;
  11154. return vbo;
  11155. };
  11156. Engine.prototype.bindArrayBuffer = function (buffer) {
  11157. if (!this._vaoRecordInProgress) {
  11158. this._unbindVertexArrayObject();
  11159. }
  11160. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11161. };
  11162. Engine.prototype.bindUniformBuffer = function (buffer) {
  11163. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11164. };
  11165. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11166. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11167. };
  11168. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11169. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11170. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11171. };
  11172. ;
  11173. Engine.prototype.bindIndexBuffer = function (buffer) {
  11174. if (!this._vaoRecordInProgress) {
  11175. this._unbindVertexArrayObject();
  11176. }
  11177. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11178. };
  11179. Engine.prototype.bindBuffer = function (buffer, target) {
  11180. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11181. this._gl.bindBuffer(target, buffer);
  11182. this._currentBoundBuffer[target] = buffer;
  11183. }
  11184. };
  11185. Engine.prototype.updateArrayBuffer = function (data) {
  11186. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11187. };
  11188. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11189. var pointer = this._currentBufferPointers[indx];
  11190. var changed = false;
  11191. if (!pointer.active) {
  11192. changed = true;
  11193. pointer.active = true;
  11194. pointer.index = indx;
  11195. pointer.size = size;
  11196. pointer.type = type;
  11197. pointer.normalized = normalized;
  11198. pointer.stride = stride;
  11199. pointer.offset = offset;
  11200. pointer.buffer = buffer;
  11201. }
  11202. else {
  11203. if (pointer.buffer !== buffer) {
  11204. pointer.buffer = buffer;
  11205. changed = true;
  11206. }
  11207. if (pointer.size !== size) {
  11208. pointer.size = size;
  11209. changed = true;
  11210. }
  11211. if (pointer.type !== type) {
  11212. pointer.type = type;
  11213. changed = true;
  11214. }
  11215. if (pointer.normalized !== normalized) {
  11216. pointer.normalized = normalized;
  11217. changed = true;
  11218. }
  11219. if (pointer.stride !== stride) {
  11220. pointer.stride = stride;
  11221. changed = true;
  11222. }
  11223. if (pointer.offset !== offset) {
  11224. pointer.offset = offset;
  11225. changed = true;
  11226. }
  11227. }
  11228. if (changed || this._vaoRecordInProgress) {
  11229. this.bindArrayBuffer(buffer);
  11230. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11231. }
  11232. };
  11233. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11234. if (indexBuffer == null) {
  11235. return;
  11236. }
  11237. if (this._cachedIndexBuffer !== indexBuffer) {
  11238. this._cachedIndexBuffer = indexBuffer;
  11239. this.bindIndexBuffer(indexBuffer);
  11240. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11241. }
  11242. };
  11243. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11244. var attributes = effect.getAttributesNames();
  11245. if (!this._vaoRecordInProgress) {
  11246. this._unbindVertexArrayObject();
  11247. }
  11248. this.unbindAllAttributes();
  11249. for (var index = 0; index < attributes.length; index++) {
  11250. var order = effect.getAttributeLocation(index);
  11251. if (order >= 0) {
  11252. var vertexBuffer = vertexBuffers[attributes[index]];
  11253. if (!vertexBuffer) {
  11254. continue;
  11255. }
  11256. this._gl.enableVertexAttribArray(order);
  11257. if (!this._vaoRecordInProgress) {
  11258. this._vertexAttribArraysEnabled[order] = true;
  11259. }
  11260. var buffer = vertexBuffer.getBuffer();
  11261. if (buffer) {
  11262. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11263. if (vertexBuffer.getIsInstanced()) {
  11264. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11265. if (!this._vaoRecordInProgress) {
  11266. this._currentInstanceLocations.push(order);
  11267. this._currentInstanceBuffers.push(buffer);
  11268. }
  11269. }
  11270. }
  11271. }
  11272. }
  11273. };
  11274. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11275. var vao = this._gl.createVertexArray();
  11276. this._vaoRecordInProgress = true;
  11277. this._gl.bindVertexArray(vao);
  11278. this._mustWipeVertexAttributes = true;
  11279. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11280. this.bindIndexBuffer(indexBuffer);
  11281. this._vaoRecordInProgress = false;
  11282. this._gl.bindVertexArray(null);
  11283. return vao;
  11284. };
  11285. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11286. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11287. this._cachedVertexArrayObject = vertexArrayObject;
  11288. this._gl.bindVertexArray(vertexArrayObject);
  11289. this._cachedVertexBuffers = null;
  11290. this._cachedIndexBuffer = null;
  11291. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11292. this._mustWipeVertexAttributes = true;
  11293. }
  11294. };
  11295. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11296. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11297. this._cachedVertexBuffers = vertexBuffer;
  11298. this._cachedEffectForVertexBuffers = effect;
  11299. var attributesCount = effect.getAttributesCount();
  11300. this._unbindVertexArrayObject();
  11301. this.unbindAllAttributes();
  11302. var offset = 0;
  11303. for (var index = 0; index < attributesCount; index++) {
  11304. if (index < vertexDeclaration.length) {
  11305. var order = effect.getAttributeLocation(index);
  11306. if (order >= 0) {
  11307. this._gl.enableVertexAttribArray(order);
  11308. this._vertexAttribArraysEnabled[order] = true;
  11309. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11310. }
  11311. offset += vertexDeclaration[index] * 4;
  11312. }
  11313. }
  11314. }
  11315. this._bindIndexBufferWithCache(indexBuffer);
  11316. };
  11317. Engine.prototype._unbindVertexArrayObject = function () {
  11318. if (!this._cachedVertexArrayObject) {
  11319. return;
  11320. }
  11321. this._cachedVertexArrayObject = null;
  11322. this._gl.bindVertexArray(null);
  11323. };
  11324. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11325. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11326. this._cachedVertexBuffers = vertexBuffers;
  11327. this._cachedEffectForVertexBuffers = effect;
  11328. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11329. }
  11330. this._bindIndexBufferWithCache(indexBuffer);
  11331. };
  11332. Engine.prototype.unbindInstanceAttributes = function () {
  11333. var boundBuffer;
  11334. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11335. var instancesBuffer = this._currentInstanceBuffers[i];
  11336. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11337. boundBuffer = instancesBuffer;
  11338. this.bindArrayBuffer(instancesBuffer);
  11339. }
  11340. var offsetLocation = this._currentInstanceLocations[i];
  11341. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11342. }
  11343. this._currentInstanceBuffers.length = 0;
  11344. this._currentInstanceLocations.length = 0;
  11345. };
  11346. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11347. this._gl.deleteVertexArray(vao);
  11348. };
  11349. Engine.prototype._releaseBuffer = function (buffer) {
  11350. buffer.references--;
  11351. if (buffer.references === 0) {
  11352. this._gl.deleteBuffer(buffer);
  11353. return true;
  11354. }
  11355. return false;
  11356. };
  11357. Engine.prototype.createInstancesBuffer = function (capacity) {
  11358. var buffer = this._gl.createBuffer();
  11359. if (!buffer) {
  11360. throw new Error("Unable to create instance buffer");
  11361. }
  11362. buffer.capacity = capacity;
  11363. this.bindArrayBuffer(buffer);
  11364. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11365. return buffer;
  11366. };
  11367. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11368. this._gl.deleteBuffer(buffer);
  11369. };
  11370. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11371. this.bindArrayBuffer(instancesBuffer);
  11372. if (data) {
  11373. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11374. }
  11375. if (offsetLocations[0].index !== undefined) {
  11376. var stride = 0;
  11377. for (var i = 0; i < offsetLocations.length; i++) {
  11378. var ai = offsetLocations[i];
  11379. stride += ai.attributeSize * 4;
  11380. }
  11381. for (var i = 0; i < offsetLocations.length; i++) {
  11382. var ai = offsetLocations[i];
  11383. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11384. this._gl.enableVertexAttribArray(ai.index);
  11385. this._vertexAttribArraysEnabled[ai.index] = true;
  11386. }
  11387. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11388. this._gl.vertexAttribDivisor(ai.index, 1);
  11389. this._currentInstanceLocations.push(ai.index);
  11390. this._currentInstanceBuffers.push(instancesBuffer);
  11391. }
  11392. }
  11393. else {
  11394. for (var index = 0; index < 4; index++) {
  11395. var offsetLocation = offsetLocations[index];
  11396. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11397. this._gl.enableVertexAttribArray(offsetLocation);
  11398. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11399. }
  11400. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11401. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11402. this._currentInstanceLocations.push(offsetLocation);
  11403. this._currentInstanceBuffers.push(instancesBuffer);
  11404. }
  11405. }
  11406. };
  11407. Engine.prototype.applyStates = function () {
  11408. this._depthCullingState.apply(this._gl);
  11409. this._stencilState.apply(this._gl);
  11410. this._alphaState.apply(this._gl);
  11411. };
  11412. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11413. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11414. };
  11415. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11416. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11417. };
  11418. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11419. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11420. };
  11421. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11422. // Apply states
  11423. this.applyStates();
  11424. this._drawCalls.addCount(1, false);
  11425. // Render
  11426. var drawMode = this.DrawMode(fillMode);
  11427. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11428. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11429. if (instancesCount) {
  11430. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11431. }
  11432. else {
  11433. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11434. }
  11435. };
  11436. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11437. // Apply states
  11438. this.applyStates();
  11439. this._drawCalls.addCount(1, false);
  11440. var drawMode = this.DrawMode(fillMode);
  11441. if (instancesCount) {
  11442. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11443. }
  11444. else {
  11445. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11446. }
  11447. };
  11448. Engine.prototype.DrawMode = function (fillMode) {
  11449. switch (fillMode) {
  11450. // Triangle views
  11451. case BABYLON.Material.TriangleFillMode:
  11452. return this._gl.TRIANGLES;
  11453. case BABYLON.Material.PointFillMode:
  11454. return this._gl.POINTS;
  11455. case BABYLON.Material.WireFrameFillMode:
  11456. return this._gl.LINES;
  11457. // Draw modes
  11458. case BABYLON.Material.PointListDrawMode:
  11459. return this._gl.POINTS;
  11460. case BABYLON.Material.LineListDrawMode:
  11461. return this._gl.LINES;
  11462. case BABYLON.Material.LineLoopDrawMode:
  11463. return this._gl.LINE_LOOP;
  11464. case BABYLON.Material.LineStripDrawMode:
  11465. return this._gl.LINE_STRIP;
  11466. case BABYLON.Material.TriangleStripDrawMode:
  11467. return this._gl.TRIANGLE_STRIP;
  11468. case BABYLON.Material.TriangleFanDrawMode:
  11469. return this._gl.TRIANGLE_FAN;
  11470. default:
  11471. return this._gl.TRIANGLES;
  11472. }
  11473. };
  11474. // Shaders
  11475. Engine.prototype._releaseEffect = function (effect) {
  11476. if (this._compiledEffects[effect._key]) {
  11477. delete this._compiledEffects[effect._key];
  11478. this._deleteProgram(effect.getProgram());
  11479. }
  11480. };
  11481. Engine.prototype._deleteProgram = function (program) {
  11482. if (program) {
  11483. program.__SPECTOR_rebuildProgram = null;
  11484. if (program.transformFeedback) {
  11485. this.deleteTransformFeedback(program.transformFeedback);
  11486. program.transformFeedback = null;
  11487. }
  11488. this._gl.deleteProgram(program);
  11489. }
  11490. };
  11491. /**
  11492. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11493. * @param samplers An array of string used to represent textures
  11494. */
  11495. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11496. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11497. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11498. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11499. if (this._compiledEffects[name]) {
  11500. var compiledEffect = this._compiledEffects[name];
  11501. if (onCompiled && compiledEffect.isReady()) {
  11502. onCompiled(compiledEffect);
  11503. }
  11504. return compiledEffect;
  11505. }
  11506. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11507. effect._key = name;
  11508. this._compiledEffects[name] = effect;
  11509. return effect;
  11510. };
  11511. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11512. if (uniformsNames === void 0) { uniformsNames = []; }
  11513. if (samplers === void 0) { samplers = []; }
  11514. if (defines === void 0) { defines = ""; }
  11515. return this.createEffect({
  11516. vertex: "particles",
  11517. fragmentElement: fragmentName
  11518. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11519. };
  11520. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11521. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11522. context = context || this._gl;
  11523. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11524. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11525. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11526. };
  11527. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11528. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11529. context = context || this._gl;
  11530. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11531. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11532. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11533. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11534. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11535. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11536. return program;
  11537. };
  11538. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11539. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11540. var shaderProgram = context.createProgram();
  11541. if (!shaderProgram) {
  11542. throw new Error("Unable to create program");
  11543. }
  11544. context.attachShader(shaderProgram, vertexShader);
  11545. context.attachShader(shaderProgram, fragmentShader);
  11546. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11547. var transformFeedback = this.createTransformFeedback();
  11548. this.bindTransformFeedback(transformFeedback);
  11549. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11550. shaderProgram.transformFeedback = transformFeedback;
  11551. }
  11552. context.linkProgram(shaderProgram);
  11553. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11554. this.bindTransformFeedback(null);
  11555. }
  11556. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11557. if (!linked) {
  11558. context.validateProgram(shaderProgram);
  11559. var error = context.getProgramInfoLog(shaderProgram);
  11560. if (error) {
  11561. throw new Error(error);
  11562. }
  11563. }
  11564. context.deleteShader(vertexShader);
  11565. context.deleteShader(fragmentShader);
  11566. return shaderProgram;
  11567. };
  11568. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11569. var results = new Array();
  11570. for (var index = 0; index < uniformsNames.length; index++) {
  11571. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11572. }
  11573. return results;
  11574. };
  11575. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11576. var results = [];
  11577. for (var index = 0; index < attributesNames.length; index++) {
  11578. try {
  11579. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11580. }
  11581. catch (e) {
  11582. results.push(-1);
  11583. }
  11584. }
  11585. return results;
  11586. };
  11587. Engine.prototype.enableEffect = function (effect) {
  11588. if (!effect) {
  11589. return;
  11590. }
  11591. // Use program
  11592. this.bindSamplers(effect);
  11593. this._currentEffect = effect;
  11594. if (effect.onBind) {
  11595. effect.onBind(effect);
  11596. }
  11597. effect.onBindObservable.notifyObservers(effect);
  11598. };
  11599. Engine.prototype.setIntArray = function (uniform, array) {
  11600. if (!uniform)
  11601. return;
  11602. this._gl.uniform1iv(uniform, array);
  11603. };
  11604. Engine.prototype.setIntArray2 = function (uniform, array) {
  11605. if (!uniform || array.length % 2 !== 0)
  11606. return;
  11607. this._gl.uniform2iv(uniform, array);
  11608. };
  11609. Engine.prototype.setIntArray3 = function (uniform, array) {
  11610. if (!uniform || array.length % 3 !== 0)
  11611. return;
  11612. this._gl.uniform3iv(uniform, array);
  11613. };
  11614. Engine.prototype.setIntArray4 = function (uniform, array) {
  11615. if (!uniform || array.length % 4 !== 0)
  11616. return;
  11617. this._gl.uniform4iv(uniform, array);
  11618. };
  11619. Engine.prototype.setFloatArray = function (uniform, array) {
  11620. if (!uniform)
  11621. return;
  11622. this._gl.uniform1fv(uniform, array);
  11623. };
  11624. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11625. if (!uniform || array.length % 2 !== 0)
  11626. return;
  11627. this._gl.uniform2fv(uniform, array);
  11628. };
  11629. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11630. if (!uniform || array.length % 3 !== 0)
  11631. return;
  11632. this._gl.uniform3fv(uniform, array);
  11633. };
  11634. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11635. if (!uniform || array.length % 4 !== 0)
  11636. return;
  11637. this._gl.uniform4fv(uniform, array);
  11638. };
  11639. Engine.prototype.setArray = function (uniform, array) {
  11640. if (!uniform)
  11641. return;
  11642. this._gl.uniform1fv(uniform, array);
  11643. };
  11644. Engine.prototype.setArray2 = function (uniform, array) {
  11645. if (!uniform || array.length % 2 !== 0)
  11646. return;
  11647. this._gl.uniform2fv(uniform, array);
  11648. };
  11649. Engine.prototype.setArray3 = function (uniform, array) {
  11650. if (!uniform || array.length % 3 !== 0)
  11651. return;
  11652. this._gl.uniform3fv(uniform, array);
  11653. };
  11654. Engine.prototype.setArray4 = function (uniform, array) {
  11655. if (!uniform || array.length % 4 !== 0)
  11656. return;
  11657. this._gl.uniform4fv(uniform, array);
  11658. };
  11659. Engine.prototype.setMatrices = function (uniform, matrices) {
  11660. if (!uniform)
  11661. return;
  11662. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11663. };
  11664. Engine.prototype.setMatrix = function (uniform, matrix) {
  11665. if (!uniform)
  11666. return;
  11667. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11668. };
  11669. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11670. if (!uniform)
  11671. return;
  11672. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11673. };
  11674. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11675. if (!uniform)
  11676. return;
  11677. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11678. };
  11679. Engine.prototype.setInt = function (uniform, value) {
  11680. if (!uniform)
  11681. return;
  11682. this._gl.uniform1i(uniform, value);
  11683. };
  11684. Engine.prototype.setFloat = function (uniform, value) {
  11685. if (!uniform)
  11686. return;
  11687. this._gl.uniform1f(uniform, value);
  11688. };
  11689. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11690. if (!uniform)
  11691. return;
  11692. this._gl.uniform2f(uniform, x, y);
  11693. };
  11694. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11695. if (!uniform)
  11696. return;
  11697. this._gl.uniform3f(uniform, x, y, z);
  11698. };
  11699. Engine.prototype.setBool = function (uniform, bool) {
  11700. if (!uniform)
  11701. return;
  11702. this._gl.uniform1i(uniform, bool);
  11703. };
  11704. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11705. if (!uniform)
  11706. return;
  11707. this._gl.uniform4f(uniform, x, y, z, w);
  11708. };
  11709. Engine.prototype.setColor3 = function (uniform, color3) {
  11710. if (!uniform)
  11711. return;
  11712. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11713. };
  11714. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11715. if (!uniform)
  11716. return;
  11717. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11718. };
  11719. // States
  11720. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11721. if (zOffset === void 0) { zOffset = 0; }
  11722. if (reverseSide === void 0) { reverseSide = false; }
  11723. // Culling
  11724. if (this._depthCullingState.cull !== culling || force) {
  11725. this._depthCullingState.cull = culling;
  11726. }
  11727. // Cull face
  11728. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11729. if (this._depthCullingState.cullFace !== cullFace || force) {
  11730. this._depthCullingState.cullFace = cullFace;
  11731. }
  11732. // Z offset
  11733. this.setZOffset(zOffset);
  11734. // Front face
  11735. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11736. if (this._depthCullingState.frontFace !== frontFace || force) {
  11737. this._depthCullingState.frontFace = frontFace;
  11738. }
  11739. };
  11740. Engine.prototype.setZOffset = function (value) {
  11741. this._depthCullingState.zOffset = value;
  11742. };
  11743. Engine.prototype.getZOffset = function () {
  11744. return this._depthCullingState.zOffset;
  11745. };
  11746. Engine.prototype.setDepthBuffer = function (enable) {
  11747. this._depthCullingState.depthTest = enable;
  11748. };
  11749. Engine.prototype.getDepthWrite = function () {
  11750. return this._depthCullingState.depthMask;
  11751. };
  11752. Engine.prototype.setDepthWrite = function (enable) {
  11753. this._depthCullingState.depthMask = enable;
  11754. };
  11755. Engine.prototype.setColorWrite = function (enable) {
  11756. this._gl.colorMask(enable, enable, enable, enable);
  11757. this._colorWrite = enable;
  11758. };
  11759. Engine.prototype.getColorWrite = function () {
  11760. return this._colorWrite;
  11761. };
  11762. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11763. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11764. };
  11765. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11766. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11767. if (this._alphaMode === mode) {
  11768. return;
  11769. }
  11770. switch (mode) {
  11771. case Engine.ALPHA_DISABLE:
  11772. this._alphaState.alphaBlend = false;
  11773. break;
  11774. case Engine.ALPHA_PREMULTIPLIED:
  11775. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11776. this._alphaState.alphaBlend = true;
  11777. break;
  11778. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11779. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11780. this._alphaState.alphaBlend = true;
  11781. break;
  11782. case Engine.ALPHA_COMBINE:
  11783. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11784. this._alphaState.alphaBlend = true;
  11785. break;
  11786. case Engine.ALPHA_ONEONE:
  11787. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11788. this._alphaState.alphaBlend = true;
  11789. break;
  11790. case Engine.ALPHA_ADD:
  11791. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11792. this._alphaState.alphaBlend = true;
  11793. break;
  11794. case Engine.ALPHA_SUBTRACT:
  11795. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11796. this._alphaState.alphaBlend = true;
  11797. break;
  11798. case Engine.ALPHA_MULTIPLY:
  11799. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11800. this._alphaState.alphaBlend = true;
  11801. break;
  11802. case Engine.ALPHA_MAXIMIZED:
  11803. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11804. this._alphaState.alphaBlend = true;
  11805. break;
  11806. case Engine.ALPHA_INTERPOLATE:
  11807. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11808. this._alphaState.alphaBlend = true;
  11809. break;
  11810. case Engine.ALPHA_SCREENMODE:
  11811. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11812. this._alphaState.alphaBlend = true;
  11813. break;
  11814. }
  11815. if (!noDepthWriteChange) {
  11816. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11817. }
  11818. this._alphaMode = mode;
  11819. };
  11820. Engine.prototype.getAlphaMode = function () {
  11821. return this._alphaMode;
  11822. };
  11823. // Textures
  11824. Engine.prototype.wipeCaches = function (bruteForce) {
  11825. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11826. return;
  11827. }
  11828. this._currentEffect = null;
  11829. // 6/8/2017: deltakosh: Should not be required anymore.
  11830. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11831. if (bruteForce) {
  11832. this.resetTextureCache();
  11833. this._currentProgram = null;
  11834. this._stencilState.reset();
  11835. this._depthCullingState.reset();
  11836. this.setDepthFunctionToLessOrEqual();
  11837. this._alphaState.reset();
  11838. }
  11839. this._resetVertexBufferBinding();
  11840. this._cachedIndexBuffer = null;
  11841. this._cachedEffectForVertexBuffers = null;
  11842. this._unbindVertexArrayObject();
  11843. this.bindIndexBuffer(null);
  11844. };
  11845. /**
  11846. * Set the compressed texture format to use, based on the formats you have, and the formats
  11847. * supported by the hardware / browser.
  11848. *
  11849. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11850. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11851. * to API arguments needed to compressed textures. This puts the burden on the container
  11852. * generator to house the arcane code for determining these for current & future formats.
  11853. *
  11854. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11855. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11856. *
  11857. * Note: The result of this call is not taken into account when a texture is base64.
  11858. *
  11859. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11860. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11861. *
  11862. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11863. * @returns The extension selected.
  11864. */
  11865. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11866. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11867. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11868. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11869. return this._textureFormatInUse = this._texturesSupported[i];
  11870. }
  11871. }
  11872. }
  11873. // actively set format to nothing, to allow this to be called more than once
  11874. // and possibly fail the 2nd time
  11875. this._textureFormatInUse = null;
  11876. return null;
  11877. };
  11878. Engine.prototype._createTexture = function () {
  11879. var texture = this._gl.createTexture();
  11880. if (!texture) {
  11881. throw new Error("Unable to create texture");
  11882. }
  11883. return texture;
  11884. };
  11885. /**
  11886. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11887. * @param {string} urlArg- This contains one of the following:
  11888. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11889. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11890. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11891. *
  11892. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11893. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11894. * @param {Scene} scene- Needed for loading to the correct scene.
  11895. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11896. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11897. * @param {callback} onError- Optional callback to be called upon failure.
  11898. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11899. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11900. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11901. *
  11902. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11903. */
  11904. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11905. var _this = this;
  11906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11907. if (onLoad === void 0) { onLoad = null; }
  11908. if (onError === void 0) { onError = null; }
  11909. if (buffer === void 0) { buffer = null; }
  11910. if (fallBack === void 0) { fallBack = null; }
  11911. if (format === void 0) { format = null; }
  11912. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11913. var fromData = url.substr(0, 5) === "data:";
  11914. var fromBlob = url.substr(0, 5) === "blob:";
  11915. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11916. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11917. // establish the file extension, if possible
  11918. var lastDot = url.lastIndexOf('.');
  11919. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11920. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  11921. var isTGA = (extension.indexOf(".tga") === 0);
  11922. // determine if a ktx file should be substituted
  11923. var isKTX = false;
  11924. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11925. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11926. isKTX = true;
  11927. }
  11928. if (scene) {
  11929. scene._addPendingData(texture);
  11930. }
  11931. texture.url = url;
  11932. texture.generateMipMaps = !noMipmap;
  11933. texture.samplingMode = samplingMode;
  11934. texture.invertY = invertY;
  11935. if (!this._doNotHandleContextLost) {
  11936. // Keep a link to the buffer only if we plan to handle context lost
  11937. texture._buffer = buffer;
  11938. }
  11939. var onLoadObserver = null;
  11940. if (onLoad && !fallBack) {
  11941. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11942. }
  11943. if (!fallBack)
  11944. this._internalTexturesCache.push(texture);
  11945. var onerror = function (message, exception) {
  11946. if (scene) {
  11947. scene._removePendingData(texture);
  11948. }
  11949. if (onLoadObserver) {
  11950. texture.onLoadedObservable.remove(onLoadObserver);
  11951. }
  11952. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11953. if (isKTX) {
  11954. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11955. }
  11956. else if (BABYLON.Tools.UseFallbackTexture) {
  11957. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11958. }
  11959. if (onError) {
  11960. onError(message || "Unknown error", exception);
  11961. }
  11962. };
  11963. var callback = null;
  11964. // processing for non-image formats
  11965. if (isKTX || isTGA || isDDS) {
  11966. if (isKTX) {
  11967. callback = function (data) {
  11968. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11969. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11970. ktx.uploadLevels(_this._gl, !noMipmap);
  11971. return false;
  11972. }, samplingMode);
  11973. };
  11974. }
  11975. else if (isTGA) {
  11976. callback = function (arrayBuffer) {
  11977. var data = new Uint8Array(arrayBuffer);
  11978. var header = BABYLON.TGATools.GetTGAHeader(data);
  11979. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11980. BABYLON.TGATools.UploadContent(_this._gl, data);
  11981. return false;
  11982. }, samplingMode);
  11983. };
  11984. }
  11985. else if (isDDS) {
  11986. callback = function (data) {
  11987. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11988. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11989. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11990. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11991. return false;
  11992. }, samplingMode);
  11993. };
  11994. }
  11995. if (!buffer) {
  11996. this._loadFile(url, function (data) {
  11997. if (callback) {
  11998. callback(data);
  11999. }
  12000. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12001. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12002. });
  12003. }
  12004. else {
  12005. if (callback) {
  12006. callback(buffer);
  12007. }
  12008. }
  12009. // image format processing
  12010. }
  12011. else {
  12012. var onload = function (img) {
  12013. if (fromBlob && !_this._doNotHandleContextLost) {
  12014. // We need to store the image if we need to rebuild the texture
  12015. // in case of a webgl context lost
  12016. texture._buffer = img;
  12017. }
  12018. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12019. var gl = _this._gl;
  12020. var isPot = (img.width === potWidth && img.height === potHeight);
  12021. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12022. if (isPot) {
  12023. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12024. return false;
  12025. }
  12026. // Using shaders to rescale because canvas.drawImage is lossy
  12027. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12028. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12029. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12032. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12033. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12034. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12035. _this._releaseTexture(source);
  12036. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12037. continuationCallback();
  12038. });
  12039. return true;
  12040. }, samplingMode);
  12041. };
  12042. if (!fromData || isBase64)
  12043. if (buffer instanceof HTMLImageElement) {
  12044. onload(buffer);
  12045. }
  12046. else {
  12047. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12048. }
  12049. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12050. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12051. else
  12052. onload(buffer);
  12053. }
  12054. return texture;
  12055. };
  12056. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12057. var _this = this;
  12058. var rtt = this.createRenderTargetTexture({
  12059. width: destination.width,
  12060. height: destination.height,
  12061. }, {
  12062. generateMipMaps: false,
  12063. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12064. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12065. generateDepthBuffer: false,
  12066. generateStencilBuffer: false
  12067. });
  12068. if (!this._rescalePostProcess) {
  12069. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12070. }
  12071. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12072. _this._rescalePostProcess.onApply = function (effect) {
  12073. effect._bindTexture("textureSampler", source);
  12074. };
  12075. var hostingScene = scene;
  12076. if (!hostingScene) {
  12077. hostingScene = _this.scenes[_this.scenes.length - 1];
  12078. }
  12079. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12080. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12081. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12082. _this.unBindFramebuffer(rtt);
  12083. _this._releaseTexture(rtt);
  12084. if (onComplete) {
  12085. onComplete();
  12086. }
  12087. });
  12088. };
  12089. Engine.prototype._getInternalFormat = function (format) {
  12090. var internalFormat = this._gl.RGBA;
  12091. switch (format) {
  12092. case Engine.TEXTUREFORMAT_ALPHA:
  12093. internalFormat = this._gl.ALPHA;
  12094. break;
  12095. case Engine.TEXTUREFORMAT_LUMINANCE:
  12096. internalFormat = this._gl.LUMINANCE;
  12097. break;
  12098. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12099. internalFormat = this._gl.LUMINANCE_ALPHA;
  12100. break;
  12101. case Engine.TEXTUREFORMAT_RGB:
  12102. internalFormat = this._gl.RGB;
  12103. break;
  12104. case Engine.TEXTUREFORMAT_RGBA:
  12105. internalFormat = this._gl.RGBA;
  12106. break;
  12107. }
  12108. return internalFormat;
  12109. };
  12110. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12111. if (compression === void 0) { compression = null; }
  12112. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12113. if (!texture) {
  12114. return;
  12115. }
  12116. var internalFormat = this._getInternalFormat(format);
  12117. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12118. var textureType = this._getWebGLTextureType(type);
  12119. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12120. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12121. if (!this._doNotHandleContextLost) {
  12122. texture._bufferView = data;
  12123. texture.format = format;
  12124. texture.type = type;
  12125. texture.invertY = invertY;
  12126. texture._compression = compression;
  12127. }
  12128. if (texture.width % 4 !== 0) {
  12129. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12130. }
  12131. if (compression && data) {
  12132. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12133. }
  12134. else {
  12135. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12136. }
  12137. if (texture.generateMipMaps) {
  12138. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12139. }
  12140. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12141. // this.resetTextureCache();
  12142. texture.isReady = true;
  12143. };
  12144. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12145. if (compression === void 0) { compression = null; }
  12146. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12147. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12148. texture.baseWidth = width;
  12149. texture.baseHeight = height;
  12150. texture.width = width;
  12151. texture.height = height;
  12152. texture.format = format;
  12153. texture.generateMipMaps = generateMipMaps;
  12154. texture.samplingMode = samplingMode;
  12155. texture.invertY = invertY;
  12156. texture._compression = compression;
  12157. texture.type = type;
  12158. if (!this._doNotHandleContextLost) {
  12159. texture._bufferView = data;
  12160. }
  12161. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12162. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12163. // Filters
  12164. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12165. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12166. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12167. if (generateMipMaps) {
  12168. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12169. }
  12170. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12171. this._internalTexturesCache.push(texture);
  12172. return texture;
  12173. };
  12174. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12175. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12176. texture.baseWidth = width;
  12177. texture.baseHeight = height;
  12178. if (generateMipMaps) {
  12179. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12180. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12181. }
  12182. // this.resetTextureCache();
  12183. texture.width = width;
  12184. texture.height = height;
  12185. texture.isReady = false;
  12186. texture.generateMipMaps = generateMipMaps;
  12187. texture.samplingMode = samplingMode;
  12188. this.updateTextureSamplingMode(samplingMode, texture);
  12189. this._internalTexturesCache.push(texture);
  12190. return texture;
  12191. };
  12192. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12193. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12194. if (texture.isCube) {
  12195. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12196. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12197. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12198. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12199. }
  12200. else if (texture.is3D) {
  12201. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12204. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12205. }
  12206. else {
  12207. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12208. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12210. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12211. }
  12212. texture.samplingMode = samplingMode;
  12213. };
  12214. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12215. if (premulAlpha === void 0) { premulAlpha = false; }
  12216. if (!texture) {
  12217. return;
  12218. }
  12219. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12220. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12221. if (premulAlpha) {
  12222. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12223. }
  12224. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12225. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12226. if (texture.generateMipMaps) {
  12227. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12228. }
  12229. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12230. if (premulAlpha) {
  12231. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12232. }
  12233. texture.isReady = true;
  12234. };
  12235. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12236. if (!texture || texture._isDisabled) {
  12237. return;
  12238. }
  12239. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12240. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12241. try {
  12242. // Testing video texture support
  12243. if (this._videoTextureSupported === undefined) {
  12244. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12245. if (this._gl.getError() !== 0) {
  12246. this._videoTextureSupported = false;
  12247. }
  12248. else {
  12249. this._videoTextureSupported = true;
  12250. }
  12251. }
  12252. // Copy video through the current working canvas if video texture is not supported
  12253. if (!this._videoTextureSupported) {
  12254. if (!texture._workingCanvas) {
  12255. texture._workingCanvas = document.createElement("canvas");
  12256. var context = texture._workingCanvas.getContext("2d");
  12257. if (!context) {
  12258. throw new Error("Unable to get 2d context");
  12259. }
  12260. texture._workingContext = context;
  12261. texture._workingCanvas.width = texture.width;
  12262. texture._workingCanvas.height = texture.height;
  12263. }
  12264. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12265. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12266. }
  12267. else {
  12268. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12269. }
  12270. if (texture.generateMipMaps) {
  12271. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12272. }
  12273. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12274. // this.resetTextureCache();
  12275. texture.isReady = true;
  12276. }
  12277. catch (ex) {
  12278. // Something unexpected
  12279. // Let's disable the texture
  12280. texture._isDisabled = true;
  12281. }
  12282. };
  12283. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12284. var fullOptions = new RenderTargetCreationOptions();
  12285. if (options !== undefined && typeof options === "object") {
  12286. fullOptions.generateMipMaps = options.generateMipMaps;
  12287. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12288. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12289. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12290. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12291. }
  12292. else {
  12293. fullOptions.generateMipMaps = options;
  12294. fullOptions.generateDepthBuffer = true;
  12295. fullOptions.generateStencilBuffer = false;
  12296. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12297. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12298. }
  12299. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12300. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12301. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12302. }
  12303. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12304. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12305. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12306. }
  12307. var gl = this._gl;
  12308. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12309. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12310. var width = size.width || size;
  12311. var height = size.height || size;
  12312. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12313. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12314. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12315. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12316. }
  12317. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12321. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12322. // Create the framebuffer
  12323. var framebuffer = gl.createFramebuffer();
  12324. this.bindUnboundFramebuffer(framebuffer);
  12325. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12326. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12327. if (fullOptions.generateMipMaps) {
  12328. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12329. }
  12330. // Unbind
  12331. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12332. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12333. this.bindUnboundFramebuffer(null);
  12334. texture._framebuffer = framebuffer;
  12335. texture.baseWidth = width;
  12336. texture.baseHeight = height;
  12337. texture.width = width;
  12338. texture.height = height;
  12339. texture.isReady = true;
  12340. texture.samples = 1;
  12341. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12342. texture.samplingMode = fullOptions.samplingMode;
  12343. texture.type = fullOptions.type;
  12344. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12345. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12346. // this.resetTextureCache();
  12347. this._internalTexturesCache.push(texture);
  12348. return texture;
  12349. };
  12350. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12351. var generateMipMaps = false;
  12352. var generateDepthBuffer = true;
  12353. var generateStencilBuffer = false;
  12354. var generateDepthTexture = false;
  12355. var textureCount = 1;
  12356. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12357. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12358. var types = [], samplingModes = [];
  12359. if (options !== undefined) {
  12360. generateMipMaps = options.generateMipMaps;
  12361. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12362. generateStencilBuffer = options.generateStencilBuffer;
  12363. generateDepthTexture = options.generateDepthTexture;
  12364. textureCount = options.textureCount || 1;
  12365. if (options.types) {
  12366. types = options.types;
  12367. }
  12368. if (options.samplingModes) {
  12369. samplingModes = options.samplingModes;
  12370. }
  12371. }
  12372. var gl = this._gl;
  12373. // Create the framebuffer
  12374. var framebuffer = gl.createFramebuffer();
  12375. this.bindUnboundFramebuffer(framebuffer);
  12376. var width = size.width || size;
  12377. var height = size.height || size;
  12378. var textures = [];
  12379. var attachments = [];
  12380. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12381. for (var i = 0; i < textureCount; i++) {
  12382. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12383. var type = types[i] || defaultType;
  12384. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12385. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12386. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12387. }
  12388. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12389. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12390. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12391. }
  12392. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12393. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12394. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12395. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12396. }
  12397. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12398. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12399. textures.push(texture);
  12400. attachments.push(attachment);
  12401. gl.activeTexture(gl["TEXTURE" + i]);
  12402. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12403. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12407. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12408. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12409. if (generateMipMaps) {
  12410. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12411. }
  12412. // Unbind
  12413. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12414. texture._framebuffer = framebuffer;
  12415. texture._depthStencilBuffer = depthStencilBuffer;
  12416. texture.baseWidth = width;
  12417. texture.baseHeight = height;
  12418. texture.width = width;
  12419. texture.height = height;
  12420. texture.isReady = true;
  12421. texture.samples = 1;
  12422. texture.generateMipMaps = generateMipMaps;
  12423. texture.samplingMode = samplingMode;
  12424. texture.type = type;
  12425. texture._generateDepthBuffer = generateDepthBuffer;
  12426. texture._generateStencilBuffer = generateStencilBuffer;
  12427. texture._attachments = attachments;
  12428. this._internalTexturesCache.push(texture);
  12429. }
  12430. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12431. // Depth texture
  12432. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12433. gl.activeTexture(gl.TEXTURE0);
  12434. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12439. 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);
  12440. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12441. depthTexture._framebuffer = framebuffer;
  12442. depthTexture.baseWidth = width;
  12443. depthTexture.baseHeight = height;
  12444. depthTexture.width = width;
  12445. depthTexture.height = height;
  12446. depthTexture.isReady = true;
  12447. depthTexture.samples = 1;
  12448. depthTexture.generateMipMaps = generateMipMaps;
  12449. depthTexture.samplingMode = gl.NEAREST;
  12450. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12451. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12452. textures.push(depthTexture);
  12453. this._internalTexturesCache.push(depthTexture);
  12454. }
  12455. gl.drawBuffers(attachments);
  12456. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12457. this.bindUnboundFramebuffer(null);
  12458. this.resetTextureCache();
  12459. return textures;
  12460. };
  12461. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12462. if (samples === void 0) { samples = 1; }
  12463. var depthStencilBuffer = null;
  12464. var gl = this._gl;
  12465. // Create the depth/stencil buffer
  12466. if (generateStencilBuffer) {
  12467. depthStencilBuffer = gl.createRenderbuffer();
  12468. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12469. if (samples > 1) {
  12470. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12471. }
  12472. else {
  12473. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12474. }
  12475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12476. }
  12477. else if (generateDepthBuffer) {
  12478. depthStencilBuffer = gl.createRenderbuffer();
  12479. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12480. if (samples > 1) {
  12481. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12482. }
  12483. else {
  12484. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12485. }
  12486. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12487. }
  12488. return depthStencilBuffer;
  12489. };
  12490. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12491. if (this.webGLVersion < 2 || !texture) {
  12492. return 1;
  12493. }
  12494. if (texture.samples === samples) {
  12495. return samples;
  12496. }
  12497. var gl = this._gl;
  12498. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12499. // Dispose previous render buffers
  12500. if (texture._depthStencilBuffer) {
  12501. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12502. texture._depthStencilBuffer = null;
  12503. }
  12504. if (texture._MSAAFramebuffer) {
  12505. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12506. texture._MSAAFramebuffer = null;
  12507. }
  12508. if (texture._MSAARenderBuffer) {
  12509. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12510. texture._MSAARenderBuffer = null;
  12511. }
  12512. if (samples > 1) {
  12513. var framebuffer = gl.createFramebuffer();
  12514. if (!framebuffer) {
  12515. throw new Error("Unable to create multi sampled framebuffer");
  12516. }
  12517. texture._MSAAFramebuffer = framebuffer;
  12518. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12519. var colorRenderbuffer = gl.createRenderbuffer();
  12520. if (!colorRenderbuffer) {
  12521. throw new Error("Unable to create multi sampled framebuffer");
  12522. }
  12523. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12524. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12525. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12526. texture._MSAARenderBuffer = colorRenderbuffer;
  12527. }
  12528. else {
  12529. this.bindUnboundFramebuffer(texture._framebuffer);
  12530. }
  12531. texture.samples = samples;
  12532. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12533. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12534. this.bindUnboundFramebuffer(null);
  12535. return samples;
  12536. };
  12537. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12538. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12539. return 1;
  12540. }
  12541. if (textures[0].samples === samples) {
  12542. return samples;
  12543. }
  12544. var gl = this._gl;
  12545. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12546. // Dispose previous render buffers
  12547. if (textures[0]._depthStencilBuffer) {
  12548. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12549. textures[0]._depthStencilBuffer = null;
  12550. }
  12551. if (textures[0]._MSAAFramebuffer) {
  12552. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12553. textures[0]._MSAAFramebuffer = null;
  12554. }
  12555. for (var i = 0; i < textures.length; i++) {
  12556. if (textures[i]._MSAARenderBuffer) {
  12557. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12558. textures[i]._MSAARenderBuffer = null;
  12559. }
  12560. }
  12561. if (samples > 1) {
  12562. var framebuffer = gl.createFramebuffer();
  12563. if (!framebuffer) {
  12564. throw new Error("Unable to create multi sampled framebuffer");
  12565. }
  12566. this.bindUnboundFramebuffer(framebuffer);
  12567. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12568. var attachments = [];
  12569. for (var i = 0; i < textures.length; i++) {
  12570. var texture = textures[i];
  12571. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12572. var colorRenderbuffer = gl.createRenderbuffer();
  12573. if (!colorRenderbuffer) {
  12574. throw new Error("Unable to create multi sampled framebuffer");
  12575. }
  12576. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12577. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12578. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12579. texture._MSAAFramebuffer = framebuffer;
  12580. texture._MSAARenderBuffer = colorRenderbuffer;
  12581. texture.samples = samples;
  12582. texture._depthStencilBuffer = depthStencilBuffer;
  12583. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12584. attachments.push(attachment);
  12585. }
  12586. gl.drawBuffers(attachments);
  12587. }
  12588. else {
  12589. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12590. }
  12591. this.bindUnboundFramebuffer(null);
  12592. return samples;
  12593. };
  12594. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12595. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12596. };
  12597. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12598. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12599. };
  12600. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12601. var gl = this._gl;
  12602. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12603. var generateMipMaps = true;
  12604. var generateDepthBuffer = true;
  12605. var generateStencilBuffer = false;
  12606. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12607. if (options !== undefined) {
  12608. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12609. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12610. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12611. if (options.samplingMode !== undefined) {
  12612. samplingMode = options.samplingMode;
  12613. }
  12614. }
  12615. texture.isCube = true;
  12616. texture.generateMipMaps = generateMipMaps;
  12617. texture.samples = 1;
  12618. texture.samplingMode = samplingMode;
  12619. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12620. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12621. for (var face = 0; face < 6; face++) {
  12622. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12623. }
  12624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12628. // Create the framebuffer
  12629. var framebuffer = gl.createFramebuffer();
  12630. this.bindUnboundFramebuffer(framebuffer);
  12631. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12632. // Mipmaps
  12633. if (texture.generateMipMaps) {
  12634. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12635. }
  12636. // Unbind
  12637. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12638. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12639. this.bindUnboundFramebuffer(null);
  12640. texture._framebuffer = framebuffer;
  12641. texture.width = size;
  12642. texture.height = size;
  12643. texture.isReady = true;
  12644. //this.resetTextureCache();
  12645. this._internalTexturesCache.push(texture);
  12646. return texture;
  12647. };
  12648. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12649. var _this = this;
  12650. if (onLoad === void 0) { onLoad = null; }
  12651. if (onError === void 0) { onError = null; }
  12652. if (forcedExtension === void 0) { forcedExtension = null; }
  12653. var callback = function (loadData) {
  12654. if (!loadData) {
  12655. if (onLoad) {
  12656. onLoad(null);
  12657. }
  12658. return;
  12659. }
  12660. var texture = loadData.texture;
  12661. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12662. texture._lodGenerationScale = scale;
  12663. texture._lodGenerationOffset = offset;
  12664. if (_this._caps.textureLOD) {
  12665. // Do not add extra process if texture lod is supported.
  12666. if (onLoad) {
  12667. onLoad(texture);
  12668. }
  12669. return;
  12670. }
  12671. var mipSlices = 3;
  12672. var gl = _this._gl;
  12673. var width = loadData.width;
  12674. if (!width) {
  12675. return;
  12676. }
  12677. var textures = [];
  12678. for (var i = 0; i < mipSlices; i++) {
  12679. //compute LOD from even spacing in smoothness (matching shader calculation)
  12680. var smoothness = i / (mipSlices - 1);
  12681. var roughness = 1 - smoothness;
  12682. var minLODIndex = offset; // roughness = 0
  12683. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12684. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12685. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12686. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12687. glTextureFromLod.isCube = true;
  12688. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12693. if (loadData.isDDS) {
  12694. var info = loadData.info;
  12695. var data = loadData.data;
  12696. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12697. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12698. }
  12699. else {
  12700. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12701. }
  12702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12703. // Wrap in a base texture for easy binding.
  12704. var lodTexture = new BABYLON.BaseTexture(scene);
  12705. lodTexture.isCube = true;
  12706. lodTexture._texture = glTextureFromLod;
  12707. glTextureFromLod.isReady = true;
  12708. textures.push(lodTexture);
  12709. }
  12710. texture._lodTextureHigh = textures[2];
  12711. texture._lodTextureMid = textures[1];
  12712. texture._lodTextureLow = textures[0];
  12713. if (onLoad) {
  12714. onLoad(texture);
  12715. }
  12716. };
  12717. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12718. };
  12719. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12720. var _this = this;
  12721. if (onLoad === void 0) { onLoad = null; }
  12722. if (onError === void 0) { onError = null; }
  12723. if (forcedExtension === void 0) { forcedExtension = null; }
  12724. var gl = this._gl;
  12725. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12726. texture.isCube = true;
  12727. texture.url = rootUrl;
  12728. texture.generateMipMaps = !noMipmap;
  12729. if (!this._doNotHandleContextLost) {
  12730. texture._extension = forcedExtension;
  12731. texture._files = files;
  12732. }
  12733. var isKTX = false;
  12734. var isDDS = false;
  12735. var lastDot = rootUrl.lastIndexOf('.');
  12736. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12737. if (this._textureFormatInUse) {
  12738. extension = this._textureFormatInUse;
  12739. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12740. isKTX = true;
  12741. }
  12742. else {
  12743. isDDS = (extension === ".dds");
  12744. }
  12745. var onerror = function (request, exception) {
  12746. if (onError && request) {
  12747. onError(request.status + " " + request.statusText, exception);
  12748. }
  12749. };
  12750. if (isKTX) {
  12751. this._loadFile(rootUrl, function (data) {
  12752. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12753. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12754. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12755. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12756. ktx.uploadLevels(_this._gl, !noMipmap);
  12757. _this.setCubeMapTextureParams(gl, loadMipmap);
  12758. texture.width = ktx.pixelWidth;
  12759. texture.height = ktx.pixelHeight;
  12760. texture.isReady = true;
  12761. }, undefined, undefined, true, onerror);
  12762. }
  12763. else if (isDDS) {
  12764. if (files && files.length === 6) {
  12765. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12766. var info;
  12767. var loadMipmap = false;
  12768. var width = 0;
  12769. for (var index = 0; index < imgs.length; index++) {
  12770. var data = imgs[index];
  12771. info = BABYLON.DDSTools.GetDDSInfo(data);
  12772. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12773. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12774. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12775. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12776. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12777. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12778. }
  12779. texture.width = info.width;
  12780. texture.height = info.height;
  12781. texture.type = info.textureType;
  12782. width = info.width;
  12783. }
  12784. _this.setCubeMapTextureParams(gl, loadMipmap);
  12785. texture.isReady = true;
  12786. if (onLoad) {
  12787. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12788. }
  12789. }, files, onError);
  12790. }
  12791. else {
  12792. this._loadFile(rootUrl, function (data) {
  12793. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12794. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12795. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12796. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12797. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12798. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12799. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12800. }
  12801. _this.setCubeMapTextureParams(gl, loadMipmap);
  12802. texture.width = info.width;
  12803. texture.height = info.height;
  12804. texture.isReady = true;
  12805. texture.type = info.textureType;
  12806. if (onLoad) {
  12807. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12808. }
  12809. }, undefined, undefined, true, onerror);
  12810. }
  12811. }
  12812. else {
  12813. if (!files) {
  12814. throw new Error("Cannot load cubemap because files were not defined");
  12815. }
  12816. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12817. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12818. var height = width;
  12819. _this._prepareWorkingCanvas();
  12820. if (!_this._workingCanvas || !_this._workingContext) {
  12821. return;
  12822. }
  12823. _this._workingCanvas.width = width;
  12824. _this._workingCanvas.height = height;
  12825. var faces = [
  12826. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12827. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12828. ];
  12829. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12830. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12831. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12832. for (var index = 0; index < faces.length; index++) {
  12833. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12834. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12835. }
  12836. if (!noMipmap) {
  12837. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12838. }
  12839. _this.setCubeMapTextureParams(gl, !noMipmap);
  12840. texture.width = width;
  12841. texture.height = height;
  12842. texture.isReady = true;
  12843. if (format) {
  12844. texture.format = format;
  12845. }
  12846. texture.onLoadedObservable.notifyObservers(texture);
  12847. texture.onLoadedObservable.clear();
  12848. if (onLoad) {
  12849. onLoad();
  12850. }
  12851. }, files, onError);
  12852. }
  12853. this._internalTexturesCache.push(texture);
  12854. return texture;
  12855. };
  12856. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12859. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12861. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12862. // this.resetTextureCache();
  12863. };
  12864. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12865. if (compression === void 0) { compression = null; }
  12866. if (level === void 0) { level = 0; }
  12867. texture._bufferViewArray = data;
  12868. texture.format = format;
  12869. texture.type = type;
  12870. texture.invertY = invertY;
  12871. texture._compression = compression;
  12872. var gl = this._gl;
  12873. var textureType = this._getWebGLTextureType(type);
  12874. var internalFormat = this._getInternalFormat(format);
  12875. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12876. var needConversion = false;
  12877. if (internalFormat === gl.RGB) {
  12878. internalFormat = gl.RGBA;
  12879. needConversion = true;
  12880. }
  12881. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12882. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12883. if (texture.width % 4 !== 0) {
  12884. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12885. }
  12886. // Data are known to be in +X +Y +Z -X -Y -Z
  12887. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12888. var faceData = data[faceIndex];
  12889. if (compression) {
  12890. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12891. }
  12892. else {
  12893. if (needConversion) {
  12894. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12895. }
  12896. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12897. }
  12898. }
  12899. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12900. if (isPot && texture.generateMipMaps && level === 0) {
  12901. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12902. }
  12903. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12904. // this.resetTextureCache();
  12905. texture.isReady = true;
  12906. };
  12907. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12908. if (compression === void 0) { compression = null; }
  12909. var gl = this._gl;
  12910. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12911. texture.isCube = true;
  12912. texture.generateMipMaps = generateMipMaps;
  12913. texture.format = format;
  12914. texture.type = type;
  12915. if (!this._doNotHandleContextLost) {
  12916. texture._bufferViewArray = data;
  12917. }
  12918. var textureType = this._getWebGLTextureType(type);
  12919. var internalFormat = this._getInternalFormat(format);
  12920. if (internalFormat === gl.RGB) {
  12921. internalFormat = gl.RGBA;
  12922. }
  12923. var width = size;
  12924. var height = width;
  12925. texture.width = width;
  12926. texture.height = height;
  12927. // Double check on POT to generate Mips.
  12928. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12929. if (!isPot) {
  12930. generateMipMaps = false;
  12931. }
  12932. // Upload data if needed. The texture won't be ready until then.
  12933. if (data) {
  12934. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12935. }
  12936. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12937. // Filters
  12938. if (data && generateMipMaps) {
  12939. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12940. }
  12941. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12944. }
  12945. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12946. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12947. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12948. }
  12949. else {
  12950. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12953. }
  12954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12956. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12957. return texture;
  12958. };
  12959. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12960. var _this = this;
  12961. if (onLoad === void 0) { onLoad = null; }
  12962. if (onError === void 0) { onError = null; }
  12963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12964. if (invertY === void 0) { invertY = false; }
  12965. var gl = this._gl;
  12966. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12967. scene._addPendingData(texture);
  12968. texture.url = url;
  12969. this._internalTexturesCache.push(texture);
  12970. var onerror = function (request, exception) {
  12971. scene._removePendingData(texture);
  12972. if (onError && request) {
  12973. onError(request.status + " " + request.statusText, exception);
  12974. }
  12975. };
  12976. var internalCallback = function (data) {
  12977. var width = texture.width;
  12978. var faceDataArrays = callback(data);
  12979. if (!faceDataArrays) {
  12980. return;
  12981. }
  12982. if (mipmmapGenerator) {
  12983. var textureType = _this._getWebGLTextureType(type);
  12984. var internalFormat = _this._getInternalFormat(format);
  12985. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12986. var needConversion = false;
  12987. if (internalFormat === gl.RGB) {
  12988. internalFormat = gl.RGBA;
  12989. needConversion = true;
  12990. }
  12991. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12992. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12993. var mipData = mipmmapGenerator(faceDataArrays);
  12994. for (var level = 0; level < mipData.length; level++) {
  12995. var mipSize = width >> level;
  12996. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12997. var mipFaceData = mipData[level][faceIndex];
  12998. if (needConversion) {
  12999. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13000. }
  13001. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13002. }
  13003. }
  13004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13005. }
  13006. else {
  13007. texture.generateMipMaps = !noMipmap;
  13008. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13009. }
  13010. texture.isReady = true;
  13011. // this.resetTextureCache();
  13012. scene._removePendingData(texture);
  13013. if (onLoad) {
  13014. onLoad();
  13015. }
  13016. };
  13017. this._loadFile(url, function (data) {
  13018. internalCallback(data);
  13019. }, undefined, scene.database, true, onerror);
  13020. return texture;
  13021. };
  13022. ;
  13023. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13024. if (compression === void 0) { compression = null; }
  13025. var internalFormat = this._getInternalFormat(format);
  13026. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13027. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13028. if (!this._doNotHandleContextLost) {
  13029. texture._bufferView = data;
  13030. texture.format = format;
  13031. texture.invertY = invertY;
  13032. texture._compression = compression;
  13033. }
  13034. if (texture.width % 4 !== 0) {
  13035. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13036. }
  13037. if (compression && data) {
  13038. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13039. }
  13040. else {
  13041. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13042. }
  13043. if (texture.generateMipMaps) {
  13044. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13045. }
  13046. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13047. // this.resetTextureCache();
  13048. texture.isReady = true;
  13049. };
  13050. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13051. if (compression === void 0) { compression = null; }
  13052. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13053. texture.baseWidth = width;
  13054. texture.baseHeight = height;
  13055. texture.baseDepth = depth;
  13056. texture.width = width;
  13057. texture.height = height;
  13058. texture.depth = depth;
  13059. texture.format = format;
  13060. texture.generateMipMaps = generateMipMaps;
  13061. texture.samplingMode = samplingMode;
  13062. texture.is3D = true;
  13063. if (!this._doNotHandleContextLost) {
  13064. texture._bufferView = data;
  13065. }
  13066. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13067. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13068. // Filters
  13069. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13070. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13071. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13072. if (generateMipMaps) {
  13073. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13074. }
  13075. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13076. this._internalTexturesCache.push(texture);
  13077. return texture;
  13078. };
  13079. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13080. var gl = this._gl;
  13081. if (!gl) {
  13082. return;
  13083. }
  13084. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13086. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13087. if (!noMipmap && !isCompressed) {
  13088. gl.generateMipmap(gl.TEXTURE_2D);
  13089. }
  13090. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13091. // this.resetTextureCache();
  13092. if (scene) {
  13093. scene._removePendingData(texture);
  13094. }
  13095. texture.onLoadedObservable.notifyObservers(texture);
  13096. texture.onLoadedObservable.clear();
  13097. };
  13098. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13099. var _this = this;
  13100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13101. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13102. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13103. var gl = this._gl;
  13104. if (!gl) {
  13105. return;
  13106. }
  13107. if (!texture._webGLTexture) {
  13108. // this.resetTextureCache();
  13109. if (scene) {
  13110. scene._removePendingData(texture);
  13111. }
  13112. return;
  13113. }
  13114. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13115. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13116. texture.baseWidth = width;
  13117. texture.baseHeight = height;
  13118. texture.width = potWidth;
  13119. texture.height = potHeight;
  13120. texture.isReady = true;
  13121. if (processFunction(potWidth, potHeight, function () {
  13122. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13123. })) {
  13124. // Returning as texture needs extra async steps
  13125. return;
  13126. }
  13127. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13128. };
  13129. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13130. // Create new RGBA data container.
  13131. var rgbaData;
  13132. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13133. rgbaData = new Float32Array(width * height * 4);
  13134. }
  13135. else {
  13136. rgbaData = new Uint32Array(width * height * 4);
  13137. }
  13138. // Convert each pixel.
  13139. for (var x = 0; x < width; x++) {
  13140. for (var y = 0; y < height; y++) {
  13141. var index = (y * width + x) * 3;
  13142. var newIndex = (y * width + x) * 4;
  13143. // Map Old Value to new value.
  13144. rgbaData[newIndex + 0] = rgbData[index + 0];
  13145. rgbaData[newIndex + 1] = rgbData[index + 1];
  13146. rgbaData[newIndex + 2] = rgbData[index + 2];
  13147. // Add fully opaque alpha channel.
  13148. rgbaData[newIndex + 3] = 1;
  13149. }
  13150. }
  13151. return rgbaData;
  13152. };
  13153. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13154. var gl = this._gl;
  13155. if (texture._framebuffer) {
  13156. gl.deleteFramebuffer(texture._framebuffer);
  13157. texture._framebuffer = null;
  13158. }
  13159. if (texture._depthStencilBuffer) {
  13160. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13161. texture._depthStencilBuffer = null;
  13162. }
  13163. if (texture._MSAAFramebuffer) {
  13164. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13165. texture._MSAAFramebuffer = null;
  13166. }
  13167. if (texture._MSAARenderBuffer) {
  13168. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13169. texture._MSAARenderBuffer = null;
  13170. }
  13171. };
  13172. Engine.prototype._releaseTexture = function (texture) {
  13173. var gl = this._gl;
  13174. this._releaseFramebufferObjects(texture);
  13175. gl.deleteTexture(texture._webGLTexture);
  13176. // Unbind channels
  13177. this.unbindAllTextures();
  13178. var index = this._internalTexturesCache.indexOf(texture);
  13179. if (index !== -1) {
  13180. this._internalTexturesCache.splice(index, 1);
  13181. }
  13182. // Integrated fixed lod samplers.
  13183. if (texture._lodTextureHigh) {
  13184. texture._lodTextureHigh.dispose();
  13185. }
  13186. if (texture._lodTextureMid) {
  13187. texture._lodTextureMid.dispose();
  13188. }
  13189. if (texture._lodTextureLow) {
  13190. texture._lodTextureLow.dispose();
  13191. }
  13192. };
  13193. Engine.prototype.setProgram = function (program) {
  13194. if (this._currentProgram !== program) {
  13195. this._gl.useProgram(program);
  13196. this._currentProgram = program;
  13197. }
  13198. };
  13199. Engine.prototype.bindSamplers = function (effect) {
  13200. this.setProgram(effect.getProgram());
  13201. var samplers = effect.getSamplers();
  13202. for (var index = 0; index < samplers.length; index++) {
  13203. var uniform = effect.getUniform(samplers[index]);
  13204. if (uniform) {
  13205. this._boundUniforms[index] = uniform;
  13206. }
  13207. }
  13208. this._currentEffect = null;
  13209. };
  13210. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13211. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13212. return;
  13213. }
  13214. // Remove
  13215. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13216. // Bind last to it
  13217. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13218. // Bind to dummy
  13219. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13220. };
  13221. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13222. if (!internalTexture) {
  13223. return -1;
  13224. }
  13225. internalTexture._initialSlot = channel;
  13226. if (this.disableTextureBindingOptimization) {
  13227. if (channel !== internalTexture._designatedSlot) {
  13228. this._textureCollisions.addCount(1, false);
  13229. }
  13230. }
  13231. else {
  13232. if (channel !== internalTexture._designatedSlot) {
  13233. if (internalTexture._designatedSlot > -1) {
  13234. return internalTexture._designatedSlot;
  13235. }
  13236. else {
  13237. // No slot for this texture, let's pick a new one (if we find a free slot)
  13238. if (this._nextFreeTextureSlots.length) {
  13239. return this._nextFreeTextureSlots[0];
  13240. }
  13241. // We need to recycle the oldest bound texture, sorry.
  13242. this._textureCollisions.addCount(1, false);
  13243. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13244. }
  13245. }
  13246. }
  13247. return channel;
  13248. };
  13249. Engine.prototype._linkTrackers = function (previous, next) {
  13250. previous.next = next;
  13251. next.previous = previous;
  13252. };
  13253. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13254. var currentSlot = internalTexture._designatedSlot;
  13255. if (currentSlot === -1) {
  13256. return -1;
  13257. }
  13258. internalTexture._designatedSlot = -1;
  13259. if (this.disableTextureBindingOptimization) {
  13260. return -1;
  13261. }
  13262. // Remove from bound list
  13263. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13264. // Free the slot
  13265. this._boundTexturesCache[currentSlot] = null;
  13266. this._nextFreeTextureSlots.push(currentSlot);
  13267. return currentSlot;
  13268. };
  13269. Engine.prototype._activateCurrentTexture = function () {
  13270. if (this._currentTextureChannel !== this._activeChannel) {
  13271. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13272. this._currentTextureChannel = this._activeChannel;
  13273. }
  13274. };
  13275. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13276. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13277. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13278. this._activeChannel = texture._designatedSlot;
  13279. }
  13280. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13281. var isTextureForRendering = texture && texture._initialSlot > -1;
  13282. if (currentTextureBound !== texture) {
  13283. if (currentTextureBound) {
  13284. this._removeDesignatedSlot(currentTextureBound);
  13285. }
  13286. this._activateCurrentTexture();
  13287. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13288. this._boundTexturesCache[this._activeChannel] = texture;
  13289. if (texture) {
  13290. if (!this.disableTextureBindingOptimization) {
  13291. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13292. if (slotIndex > -1) {
  13293. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13294. }
  13295. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13296. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13297. }
  13298. texture._designatedSlot = this._activeChannel;
  13299. }
  13300. }
  13301. else if (forTextureDataUpdate) {
  13302. this._activateCurrentTexture();
  13303. }
  13304. if (isTextureForRendering && !forTextureDataUpdate) {
  13305. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13306. }
  13307. };
  13308. Engine.prototype._bindTexture = function (channel, texture) {
  13309. if (channel < 0) {
  13310. return;
  13311. }
  13312. if (texture) {
  13313. channel = this._getCorrectTextureChannel(channel, texture);
  13314. }
  13315. this._activeChannel = channel;
  13316. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13317. };
  13318. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13319. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13320. };
  13321. Engine.prototype.unbindAllTextures = function () {
  13322. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13323. this._activeChannel = channel;
  13324. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13325. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13326. if (this.webGLVersion > 1) {
  13327. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13328. }
  13329. }
  13330. };
  13331. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13332. if (channel < 0) {
  13333. return;
  13334. }
  13335. if (uniform) {
  13336. this._boundUniforms[channel] = uniform;
  13337. }
  13338. this._setTexture(channel, texture);
  13339. };
  13340. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13341. var uniform = this._boundUniforms[sourceSlot];
  13342. if (uniform._currentState === destination) {
  13343. return;
  13344. }
  13345. this._gl.uniform1i(uniform, destination);
  13346. uniform._currentState = destination;
  13347. };
  13348. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13349. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13350. // Not ready?
  13351. if (!texture) {
  13352. if (this._boundTexturesCache[channel] != null) {
  13353. this._activeChannel = channel;
  13354. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13355. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13356. if (this.webGLVersion > 1) {
  13357. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13358. }
  13359. }
  13360. return false;
  13361. }
  13362. // Video
  13363. if (texture.video) {
  13364. this._activeChannel = channel;
  13365. texture.update();
  13366. }
  13367. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13368. texture.delayLoad();
  13369. return false;
  13370. }
  13371. var internalTexture;
  13372. if (texture.isReady()) {
  13373. internalTexture = texture.getInternalTexture();
  13374. }
  13375. else if (texture.isCube) {
  13376. internalTexture = this.emptyCubeTexture;
  13377. }
  13378. else if (texture.is3D) {
  13379. internalTexture = this.emptyTexture3D;
  13380. }
  13381. else {
  13382. internalTexture = this.emptyTexture;
  13383. }
  13384. if (!isPartOfTextureArray) {
  13385. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13386. }
  13387. if (this._boundTexturesCache[channel] === internalTexture) {
  13388. this._moveBoundTextureOnTop(internalTexture);
  13389. if (!isPartOfTextureArray) {
  13390. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13391. }
  13392. return false;
  13393. }
  13394. this._activeChannel = channel;
  13395. if (internalTexture && internalTexture.is3D) {
  13396. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13397. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13398. internalTexture._cachedWrapU = texture.wrapU;
  13399. switch (texture.wrapU) {
  13400. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13401. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13402. break;
  13403. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13404. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13405. break;
  13406. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13407. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13408. break;
  13409. }
  13410. }
  13411. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13412. internalTexture._cachedWrapV = texture.wrapV;
  13413. switch (texture.wrapV) {
  13414. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13415. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13416. break;
  13417. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13418. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13419. break;
  13420. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13421. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13422. break;
  13423. }
  13424. }
  13425. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13426. internalTexture._cachedWrapR = texture.wrapR;
  13427. switch (texture.wrapV) {
  13428. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13429. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13430. break;
  13431. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13432. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13433. break;
  13434. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13435. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13436. break;
  13437. }
  13438. }
  13439. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13440. }
  13441. else if (internalTexture && internalTexture.isCube) {
  13442. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13443. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13444. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13445. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13446. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13447. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13448. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13449. }
  13450. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13451. }
  13452. else {
  13453. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13454. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13455. internalTexture._cachedWrapU = texture.wrapU;
  13456. switch (texture.wrapU) {
  13457. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13458. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13459. break;
  13460. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13461. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13462. break;
  13463. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13464. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13465. break;
  13466. }
  13467. }
  13468. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13469. internalTexture._cachedWrapV = texture.wrapV;
  13470. switch (texture.wrapV) {
  13471. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13472. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13473. break;
  13474. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13475. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13476. break;
  13477. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13478. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13479. break;
  13480. }
  13481. }
  13482. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13483. }
  13484. return true;
  13485. };
  13486. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13487. if (channel < 0 || !uniform) {
  13488. return;
  13489. }
  13490. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13491. this._textureUnits = new Int32Array(textures.length);
  13492. }
  13493. for (var i = 0; i < textures.length; i++) {
  13494. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13495. }
  13496. this._gl.uniform1iv(uniform, this._textureUnits);
  13497. for (var index = 0; index < textures.length; index++) {
  13498. this._setTexture(this._textureUnits[index], textures[index], true);
  13499. }
  13500. };
  13501. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13502. var internalTexture = texture.getInternalTexture();
  13503. if (!internalTexture) {
  13504. return;
  13505. }
  13506. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13507. var value = texture.anisotropicFilteringLevel;
  13508. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13509. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13510. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13511. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13512. }
  13513. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13514. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13515. internalTexture._cachedAnisotropicFilteringLevel = value;
  13516. }
  13517. };
  13518. Engine.prototype.readPixels = function (x, y, width, height) {
  13519. var data = new Uint8Array(height * width * 4);
  13520. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13521. return data;
  13522. };
  13523. /**
  13524. * Add an externaly attached data from its key.
  13525. * This method call will fail and return false, if such key already exists.
  13526. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13527. * @param key the unique key that identifies the data
  13528. * @param data the data object to associate to the key for this Engine instance
  13529. * @return true if no such key were already present and the data was added successfully, false otherwise
  13530. */
  13531. Engine.prototype.addExternalData = function (key, data) {
  13532. if (!this._externalData) {
  13533. this._externalData = new BABYLON.StringDictionary();
  13534. }
  13535. return this._externalData.add(key, data);
  13536. };
  13537. /**
  13538. * Get an externaly attached data from its key
  13539. * @param key the unique key that identifies the data
  13540. * @return the associated data, if present (can be null), or undefined if not present
  13541. */
  13542. Engine.prototype.getExternalData = function (key) {
  13543. if (!this._externalData) {
  13544. this._externalData = new BABYLON.StringDictionary();
  13545. }
  13546. return this._externalData.get(key);
  13547. };
  13548. /**
  13549. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13550. * @param key the unique key that identifies the data
  13551. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13552. * @return the associated data, can be null if the factory returned null.
  13553. */
  13554. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13555. if (!this._externalData) {
  13556. this._externalData = new BABYLON.StringDictionary();
  13557. }
  13558. return this._externalData.getOrAddWithFactory(key, factory);
  13559. };
  13560. /**
  13561. * Remove an externaly attached data from the Engine instance
  13562. * @param key the unique key that identifies the data
  13563. * @return true if the data was successfully removed, false if it doesn't exist
  13564. */
  13565. Engine.prototype.removeExternalData = function (key) {
  13566. if (!this._externalData) {
  13567. this._externalData = new BABYLON.StringDictionary();
  13568. }
  13569. return this._externalData.remove(key);
  13570. };
  13571. Engine.prototype.unbindAllAttributes = function () {
  13572. if (this._mustWipeVertexAttributes) {
  13573. this._mustWipeVertexAttributes = false;
  13574. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13575. this._gl.disableVertexAttribArray(i);
  13576. this._vertexAttribArraysEnabled[i] = false;
  13577. this._currentBufferPointers[i].active = false;
  13578. }
  13579. return;
  13580. }
  13581. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13582. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13583. continue;
  13584. }
  13585. this._gl.disableVertexAttribArray(i);
  13586. this._vertexAttribArraysEnabled[i] = false;
  13587. this._currentBufferPointers[i].active = false;
  13588. }
  13589. };
  13590. Engine.prototype.releaseEffects = function () {
  13591. for (var name in this._compiledEffects) {
  13592. this._deleteProgram(this._compiledEffects[name]._program);
  13593. }
  13594. this._compiledEffects = {};
  13595. };
  13596. // Dispose
  13597. Engine.prototype.dispose = function () {
  13598. this.hideLoadingUI();
  13599. this.stopRenderLoop();
  13600. // Release postProcesses
  13601. while (this.postProcesses.length) {
  13602. this.postProcesses[0].dispose();
  13603. }
  13604. // Empty texture
  13605. if (this._emptyTexture) {
  13606. this._releaseTexture(this._emptyTexture);
  13607. this._emptyTexture = null;
  13608. }
  13609. if (this._emptyCubeTexture) {
  13610. this._releaseTexture(this._emptyCubeTexture);
  13611. this._emptyCubeTexture = null;
  13612. }
  13613. // Rescale PP
  13614. if (this._rescalePostProcess) {
  13615. this._rescalePostProcess.dispose();
  13616. }
  13617. // Release scenes
  13618. while (this.scenes.length) {
  13619. this.scenes[0].dispose();
  13620. }
  13621. // Release audio engine
  13622. if (Engine.audioEngine) {
  13623. Engine.audioEngine.dispose();
  13624. }
  13625. // Release effects
  13626. this.releaseEffects();
  13627. // Unbind
  13628. this.unbindAllAttributes();
  13629. if (this._dummyFramebuffer) {
  13630. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13631. }
  13632. //WebVR
  13633. this.disableVR();
  13634. // Events
  13635. if (BABYLON.Tools.IsWindowObjectExist()) {
  13636. window.removeEventListener("blur", this._onBlur);
  13637. window.removeEventListener("focus", this._onFocus);
  13638. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13639. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13640. if (this._renderingCanvas) {
  13641. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13642. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13643. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13644. if (!this._doNotHandleContextLost) {
  13645. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13646. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13647. }
  13648. }
  13649. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13650. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13651. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13652. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13653. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13654. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13655. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13656. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13657. if (this._onVrDisplayConnect) {
  13658. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13659. if (this._onVrDisplayDisconnect) {
  13660. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13661. }
  13662. if (this._onVrDisplayPresentChange) {
  13663. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13664. }
  13665. this._onVrDisplayConnect = null;
  13666. this._onVrDisplayDisconnect = null;
  13667. }
  13668. }
  13669. // Remove from Instances
  13670. var index = Engine.Instances.indexOf(this);
  13671. if (index >= 0) {
  13672. Engine.Instances.splice(index, 1);
  13673. }
  13674. this._workingCanvas = null;
  13675. this._workingContext = null;
  13676. this._currentBufferPointers = [];
  13677. this._renderingCanvas = null;
  13678. this._currentProgram = null;
  13679. this.onResizeObservable.clear();
  13680. this.onCanvasBlurObservable.clear();
  13681. this.onCanvasFocusObservable.clear();
  13682. this.onCanvasPointerOutObservable.clear();
  13683. this.onBeginFrameObservable.clear();
  13684. this.onEndFrameObservable.clear();
  13685. BABYLON.Effect.ResetCache();
  13686. // Abort active requests
  13687. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13688. var request = _a[_i];
  13689. request.abort();
  13690. }
  13691. };
  13692. // Loading screen
  13693. Engine.prototype.displayLoadingUI = function () {
  13694. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13695. return;
  13696. }
  13697. var loadingScreen = this.loadingScreen;
  13698. if (loadingScreen) {
  13699. loadingScreen.displayLoadingUI();
  13700. }
  13701. };
  13702. Engine.prototype.hideLoadingUI = function () {
  13703. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13704. return;
  13705. }
  13706. var loadingScreen = this.loadingScreen;
  13707. if (loadingScreen) {
  13708. loadingScreen.hideLoadingUI();
  13709. }
  13710. };
  13711. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13712. get: function () {
  13713. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13714. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13715. return this._loadingScreen;
  13716. },
  13717. set: function (loadingScreen) {
  13718. this._loadingScreen = loadingScreen;
  13719. },
  13720. enumerable: true,
  13721. configurable: true
  13722. });
  13723. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13724. set: function (text) {
  13725. this.loadingScreen.loadingUIText = text;
  13726. },
  13727. enumerable: true,
  13728. configurable: true
  13729. });
  13730. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13731. set: function (color) {
  13732. this.loadingScreen.loadingUIBackgroundColor = color;
  13733. },
  13734. enumerable: true,
  13735. configurable: true
  13736. });
  13737. Engine.prototype.attachContextLostEvent = function (callback) {
  13738. if (this._renderingCanvas) {
  13739. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13740. }
  13741. };
  13742. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13743. if (this._renderingCanvas) {
  13744. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13745. }
  13746. };
  13747. Engine.prototype.getVertexShaderSource = function (program) {
  13748. var shaders = this._gl.getAttachedShaders(program);
  13749. if (!shaders) {
  13750. return null;
  13751. }
  13752. return this._gl.getShaderSource(shaders[0]);
  13753. };
  13754. Engine.prototype.getFragmentShaderSource = function (program) {
  13755. var shaders = this._gl.getAttachedShaders(program);
  13756. if (!shaders) {
  13757. return null;
  13758. }
  13759. return this._gl.getShaderSource(shaders[1]);
  13760. };
  13761. Engine.prototype.getError = function () {
  13762. return this._gl.getError();
  13763. };
  13764. // FPS
  13765. Engine.prototype.getFps = function () {
  13766. return this._fps;
  13767. };
  13768. Engine.prototype.getDeltaTime = function () {
  13769. return this._deltaTime;
  13770. };
  13771. Engine.prototype._measureFps = function () {
  13772. this._performanceMonitor.sampleFrame();
  13773. this._fps = this._performanceMonitor.averageFPS;
  13774. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13775. };
  13776. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13777. if (faceIndex === void 0) { faceIndex = -1; }
  13778. var gl = this._gl;
  13779. if (!this._dummyFramebuffer) {
  13780. var dummy = gl.createFramebuffer();
  13781. if (!dummy) {
  13782. throw new Error("Unable to create dummy framebuffer");
  13783. }
  13784. this._dummyFramebuffer = dummy;
  13785. }
  13786. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13787. if (faceIndex > -1) {
  13788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13789. }
  13790. else {
  13791. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13792. }
  13793. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13794. var buffer;
  13795. switch (readType) {
  13796. case gl.UNSIGNED_BYTE:
  13797. buffer = new Uint8Array(4 * width * height);
  13798. readType = gl.UNSIGNED_BYTE;
  13799. break;
  13800. default:
  13801. buffer = new Float32Array(4 * width * height);
  13802. readType = gl.FLOAT;
  13803. break;
  13804. }
  13805. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13806. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13807. return buffer;
  13808. };
  13809. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13810. if (this._webGLVersion > 1) {
  13811. return this._caps.colorBufferFloat;
  13812. }
  13813. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13814. };
  13815. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13816. if (this._webGLVersion > 1) {
  13817. return this._caps.colorBufferFloat;
  13818. }
  13819. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13820. };
  13821. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13822. Engine.prototype._canRenderToFramebuffer = function (type) {
  13823. var gl = this._gl;
  13824. //clear existing errors
  13825. while (gl.getError() !== gl.NO_ERROR) { }
  13826. var successful = true;
  13827. var texture = gl.createTexture();
  13828. gl.bindTexture(gl.TEXTURE_2D, texture);
  13829. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13830. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13832. var fb = gl.createFramebuffer();
  13833. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13834. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13835. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13836. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13837. successful = successful && (gl.getError() === gl.NO_ERROR);
  13838. //try render by clearing frame buffer's color buffer
  13839. if (successful) {
  13840. gl.clear(gl.COLOR_BUFFER_BIT);
  13841. successful = successful && (gl.getError() === gl.NO_ERROR);
  13842. }
  13843. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13844. if (successful) {
  13845. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13846. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13847. var readFormat = gl.RGBA;
  13848. var readType = gl.UNSIGNED_BYTE;
  13849. var buffer = new Uint8Array(4);
  13850. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13851. successful = successful && (gl.getError() === gl.NO_ERROR);
  13852. }
  13853. //clean up
  13854. gl.deleteTexture(texture);
  13855. gl.deleteFramebuffer(fb);
  13856. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13857. //clear accumulated errors
  13858. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13859. return successful;
  13860. };
  13861. Engine.prototype._getWebGLTextureType = function (type) {
  13862. if (type === Engine.TEXTURETYPE_FLOAT) {
  13863. return this._gl.FLOAT;
  13864. }
  13865. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13866. // Add Half Float Constant.
  13867. return this._gl.HALF_FLOAT_OES;
  13868. }
  13869. return this._gl.UNSIGNED_BYTE;
  13870. };
  13871. ;
  13872. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13873. if (this._webGLVersion === 1) {
  13874. return this._gl.RGBA;
  13875. }
  13876. if (type === Engine.TEXTURETYPE_FLOAT) {
  13877. return this._gl.RGBA32F;
  13878. }
  13879. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13880. return this._gl.RGBA16F;
  13881. }
  13882. return this._gl.RGBA;
  13883. };
  13884. ;
  13885. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13886. if (type === Engine.TEXTURETYPE_FLOAT) {
  13887. return this._gl.RGBA32F;
  13888. }
  13889. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13890. return this._gl.RGBA16F;
  13891. }
  13892. return this._gl.RGBA8;
  13893. };
  13894. ;
  13895. Engine.prototype.createQuery = function () {
  13896. return this._gl.createQuery();
  13897. };
  13898. Engine.prototype.deleteQuery = function (query) {
  13899. this._gl.deleteQuery(query);
  13900. return this;
  13901. };
  13902. Engine.prototype.isQueryResultAvailable = function (query) {
  13903. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13904. };
  13905. Engine.prototype.getQueryResult = function (query) {
  13906. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13907. };
  13908. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13909. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13910. this._gl.beginQuery(glAlgorithm, query);
  13911. return this;
  13912. };
  13913. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13914. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13915. this._gl.endQuery(glAlgorithm);
  13916. return this;
  13917. };
  13918. /* Time queries */
  13919. Engine.prototype._createTimeQuery = function () {
  13920. var timerQuery = this._caps.timerQuery;
  13921. if (timerQuery.createQueryEXT) {
  13922. return timerQuery.createQueryEXT();
  13923. }
  13924. return this.createQuery();
  13925. };
  13926. Engine.prototype._deleteTimeQuery = function (query) {
  13927. var timerQuery = this._caps.timerQuery;
  13928. if (timerQuery.deleteQueryEXT) {
  13929. timerQuery.deleteQueryEXT(query);
  13930. return;
  13931. }
  13932. this.deleteQuery(query);
  13933. };
  13934. Engine.prototype._getTimeQueryResult = function (query) {
  13935. var timerQuery = this._caps.timerQuery;
  13936. if (timerQuery.getQueryObjectEXT) {
  13937. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13938. }
  13939. return this.getQueryResult(query);
  13940. };
  13941. Engine.prototype._getTimeQueryAvailability = function (query) {
  13942. var timerQuery = this._caps.timerQuery;
  13943. if (timerQuery.getQueryObjectEXT) {
  13944. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13945. }
  13946. return this.isQueryResultAvailable(query);
  13947. };
  13948. Engine.prototype.startTimeQuery = function () {
  13949. var timerQuery = this._caps.timerQuery;
  13950. if (!timerQuery) {
  13951. return null;
  13952. }
  13953. var token = new BABYLON._TimeToken();
  13954. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13955. if (this._caps.canUseTimestampForTimerQuery) {
  13956. token._startTimeQuery = this._createTimeQuery();
  13957. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13958. }
  13959. else {
  13960. if (this._currentNonTimestampToken) {
  13961. return this._currentNonTimestampToken;
  13962. }
  13963. token._timeElapsedQuery = this._createTimeQuery();
  13964. if (timerQuery.beginQueryEXT) {
  13965. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13966. }
  13967. else {
  13968. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13969. }
  13970. this._currentNonTimestampToken = token;
  13971. }
  13972. return token;
  13973. };
  13974. Engine.prototype.endTimeQuery = function (token) {
  13975. var timerQuery = this._caps.timerQuery;
  13976. if (!timerQuery || !token) {
  13977. return -1;
  13978. }
  13979. if (this._caps.canUseTimestampForTimerQuery) {
  13980. if (!token._startTimeQuery) {
  13981. return -1;
  13982. }
  13983. if (!token._endTimeQuery) {
  13984. token._endTimeQuery = this._createTimeQuery();
  13985. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13986. }
  13987. }
  13988. else if (!token._timeElapsedQueryEnded) {
  13989. if (!token._timeElapsedQuery) {
  13990. return -1;
  13991. }
  13992. if (timerQuery.endQueryEXT) {
  13993. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13994. }
  13995. else {
  13996. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13997. }
  13998. token._timeElapsedQueryEnded = true;
  13999. }
  14000. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14001. var available = false;
  14002. if (token._endTimeQuery) {
  14003. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14004. }
  14005. else if (token._timeElapsedQuery) {
  14006. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14007. }
  14008. if (available && !disjoint) {
  14009. var result = 0;
  14010. if (this._caps.canUseTimestampForTimerQuery) {
  14011. if (!token._startTimeQuery || !token._endTimeQuery) {
  14012. return -1;
  14013. }
  14014. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14015. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14016. result = timeEnd - timeStart;
  14017. this._deleteTimeQuery(token._startTimeQuery);
  14018. this._deleteTimeQuery(token._endTimeQuery);
  14019. token._startTimeQuery = null;
  14020. token._endTimeQuery = null;
  14021. }
  14022. else {
  14023. if (!token._timeElapsedQuery) {
  14024. return -1;
  14025. }
  14026. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14027. this._deleteTimeQuery(token._timeElapsedQuery);
  14028. token._timeElapsedQuery = null;
  14029. token._timeElapsedQueryEnded = false;
  14030. this._currentNonTimestampToken = null;
  14031. }
  14032. return result;
  14033. }
  14034. return -1;
  14035. };
  14036. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14037. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14038. };
  14039. // Transform feedback
  14040. Engine.prototype.createTransformFeedback = function () {
  14041. return this._gl.createTransformFeedback();
  14042. };
  14043. Engine.prototype.deleteTransformFeedback = function (value) {
  14044. this._gl.deleteTransformFeedback(value);
  14045. };
  14046. Engine.prototype.bindTransformFeedback = function (value) {
  14047. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14048. };
  14049. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14050. if (usePoints === void 0) { usePoints = true; }
  14051. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14052. };
  14053. Engine.prototype.endTransformFeedback = function () {
  14054. this._gl.endTransformFeedback();
  14055. };
  14056. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14057. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14058. };
  14059. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14060. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14061. };
  14062. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14063. var _this = this;
  14064. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14065. this._activeRequests.push(request);
  14066. request.onCompleteObservable.add(function (request) {
  14067. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14068. });
  14069. return request;
  14070. };
  14071. /** @ignore */
  14072. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14073. var _this = this;
  14074. return new Promise(function (resolve, reject) {
  14075. _this._loadFile(url, function (data) {
  14076. resolve(data);
  14077. }, undefined, database, useArrayBuffer, function (request, exception) {
  14078. reject(exception);
  14079. });
  14080. });
  14081. };
  14082. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14083. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14084. var onload = function (data) {
  14085. loadedFiles[index] = data;
  14086. loadedFiles._internalCount++;
  14087. if (loadedFiles._internalCount === 6) {
  14088. onfinish(loadedFiles);
  14089. }
  14090. };
  14091. var onerror = function (request, exception) {
  14092. if (onErrorCallBack && request) {
  14093. onErrorCallBack(request.status + " " + request.statusText, exception);
  14094. }
  14095. };
  14096. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14097. };
  14098. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14099. if (onError === void 0) { onError = null; }
  14100. var loadedFiles = [];
  14101. loadedFiles._internalCount = 0;
  14102. for (var index = 0; index < 6; index++) {
  14103. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14104. }
  14105. };
  14106. // Statics
  14107. Engine.isSupported = function () {
  14108. try {
  14109. var tempcanvas = document.createElement("canvas");
  14110. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14111. return gl != null && !!window.WebGLRenderingContext;
  14112. }
  14113. catch (e) {
  14114. return false;
  14115. }
  14116. };
  14117. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14118. Engine.ExceptionList = [
  14119. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14120. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14121. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14122. ];
  14123. Engine.Instances = new Array();
  14124. // Const statics
  14125. Engine._ALPHA_DISABLE = 0;
  14126. Engine._ALPHA_ADD = 1;
  14127. Engine._ALPHA_COMBINE = 2;
  14128. Engine._ALPHA_SUBTRACT = 3;
  14129. Engine._ALPHA_MULTIPLY = 4;
  14130. Engine._ALPHA_MAXIMIZED = 5;
  14131. Engine._ALPHA_ONEONE = 6;
  14132. Engine._ALPHA_PREMULTIPLIED = 7;
  14133. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14134. Engine._ALPHA_INTERPOLATE = 9;
  14135. Engine._ALPHA_SCREENMODE = 10;
  14136. Engine._DELAYLOADSTATE_NONE = 0;
  14137. Engine._DELAYLOADSTATE_LOADED = 1;
  14138. Engine._DELAYLOADSTATE_LOADING = 2;
  14139. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14140. Engine._TEXTUREFORMAT_ALPHA = 0;
  14141. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14142. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14143. Engine._TEXTUREFORMAT_RGB = 4;
  14144. Engine._TEXTUREFORMAT_RGBA = 5;
  14145. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14146. Engine._TEXTURETYPE_FLOAT = 1;
  14147. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14148. // Depht or Stencil test Constants.
  14149. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14150. 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.
  14151. 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.
  14152. 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.
  14153. 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.
  14154. 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.
  14155. 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.
  14156. 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.
  14157. // Stencil Actions Constants.
  14158. Engine._KEEP = 0x1E00;
  14159. Engine._REPLACE = 0x1E01;
  14160. Engine._INCR = 0x1E02;
  14161. Engine._DECR = 0x1E03;
  14162. Engine._INVERT = 0x150A;
  14163. Engine._INCR_WRAP = 0x8507;
  14164. Engine._DECR_WRAP = 0x8508;
  14165. // Texture rescaling mode
  14166. Engine._SCALEMODE_FLOOR = 1;
  14167. Engine._SCALEMODE_NEAREST = 2;
  14168. Engine._SCALEMODE_CEILING = 3;
  14169. // Updatable statics so stick with vars here
  14170. Engine.CollisionsEpsilon = 0.001;
  14171. Engine.CodeRepository = "src/";
  14172. Engine.ShadersRepository = "src/Shaders/";
  14173. return Engine;
  14174. }());
  14175. BABYLON.Engine = Engine;
  14176. })(BABYLON || (BABYLON = {}));
  14177. //# sourceMappingURL=babylon.engine.js.map
  14178. var BABYLON;
  14179. (function (BABYLON) {
  14180. /**
  14181. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14182. */
  14183. var Node = /** @class */ (function () {
  14184. /**
  14185. * @constructor
  14186. * @param {string} name - the name and id to be given to this node
  14187. * @param {BABYLON.Scene} the scene this node will be added to
  14188. */
  14189. function Node(name, scene) {
  14190. if (scene === void 0) { scene = null; }
  14191. this.state = "";
  14192. this.metadata = null;
  14193. this.doNotSerialize = false;
  14194. this.animations = new Array();
  14195. this._ranges = {};
  14196. this._isEnabled = true;
  14197. this._isReady = true;
  14198. this._currentRenderId = -1;
  14199. this._parentRenderId = -1;
  14200. /**
  14201. * An event triggered when the mesh is disposed.
  14202. * @type {BABYLON.Observable}
  14203. */
  14204. this.onDisposeObservable = new BABYLON.Observable();
  14205. // Behaviors
  14206. this._behaviors = new Array();
  14207. this.name = name;
  14208. this.id = name;
  14209. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14210. this.uniqueId = this._scene.getUniqueId();
  14211. this._initCache();
  14212. }
  14213. Object.defineProperty(Node.prototype, "parent", {
  14214. get: function () {
  14215. return this._parentNode;
  14216. },
  14217. set: function (parent) {
  14218. if (this._parentNode === parent) {
  14219. return;
  14220. }
  14221. // Remove self from list of children of parent
  14222. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14223. var index = this._parentNode._children.indexOf(this);
  14224. if (index !== -1) {
  14225. this._parentNode._children.splice(index, 1);
  14226. }
  14227. }
  14228. // Store new parent
  14229. this._parentNode = parent;
  14230. // Add as child to new parent
  14231. if (this._parentNode) {
  14232. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14233. this._parentNode._children = new Array();
  14234. }
  14235. this._parentNode._children.push(this);
  14236. }
  14237. },
  14238. enumerable: true,
  14239. configurable: true
  14240. });
  14241. Node.prototype.getClassName = function () {
  14242. return "Node";
  14243. };
  14244. Object.defineProperty(Node.prototype, "onDispose", {
  14245. set: function (callback) {
  14246. if (this._onDisposeObserver) {
  14247. this.onDisposeObservable.remove(this._onDisposeObserver);
  14248. }
  14249. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Node.prototype.getScene = function () {
  14255. return this._scene;
  14256. };
  14257. Node.prototype.getEngine = function () {
  14258. return this._scene.getEngine();
  14259. };
  14260. Node.prototype.addBehavior = function (behavior) {
  14261. var _this = this;
  14262. var index = this._behaviors.indexOf(behavior);
  14263. if (index !== -1) {
  14264. return this;
  14265. }
  14266. behavior.init();
  14267. if (this._scene.isLoading) {
  14268. // We defer the attach when the scene will be loaded
  14269. var observer = this._scene.onDataLoadedObservable.add(function () {
  14270. behavior.attach(_this);
  14271. setTimeout(function () {
  14272. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14273. _this._scene.onDataLoadedObservable.remove(observer);
  14274. }, 0);
  14275. });
  14276. }
  14277. else {
  14278. behavior.attach(this);
  14279. }
  14280. this._behaviors.push(behavior);
  14281. return this;
  14282. };
  14283. Node.prototype.removeBehavior = function (behavior) {
  14284. var index = this._behaviors.indexOf(behavior);
  14285. if (index === -1) {
  14286. return this;
  14287. }
  14288. this._behaviors[index].detach();
  14289. this._behaviors.splice(index, 1);
  14290. return this;
  14291. };
  14292. Object.defineProperty(Node.prototype, "behaviors", {
  14293. get: function () {
  14294. return this._behaviors;
  14295. },
  14296. enumerable: true,
  14297. configurable: true
  14298. });
  14299. Node.prototype.getBehaviorByName = function (name) {
  14300. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14301. var behavior = _a[_i];
  14302. if (behavior.name === name) {
  14303. return behavior;
  14304. }
  14305. }
  14306. return null;
  14307. };
  14308. // override it in derived class
  14309. Node.prototype.getWorldMatrix = function () {
  14310. return BABYLON.Matrix.Identity();
  14311. };
  14312. // override it in derived class if you add new variables to the cache
  14313. // and call the parent class method
  14314. Node.prototype._initCache = function () {
  14315. this._cache = {};
  14316. this._cache.parent = undefined;
  14317. };
  14318. Node.prototype.updateCache = function (force) {
  14319. if (!force && this.isSynchronized())
  14320. return;
  14321. this._cache.parent = this.parent;
  14322. this._updateCache();
  14323. };
  14324. // override it in derived class if you add new variables to the cache
  14325. // and call the parent class method if !ignoreParentClass
  14326. Node.prototype._updateCache = function (ignoreParentClass) {
  14327. };
  14328. // override it in derived class if you add new variables to the cache
  14329. Node.prototype._isSynchronized = function () {
  14330. return true;
  14331. };
  14332. Node.prototype._markSyncedWithParent = function () {
  14333. if (this.parent) {
  14334. this._parentRenderId = this.parent._currentRenderId;
  14335. }
  14336. };
  14337. Node.prototype.isSynchronizedWithParent = function () {
  14338. if (!this.parent) {
  14339. return true;
  14340. }
  14341. if (this._parentRenderId !== this.parent._currentRenderId) {
  14342. return false;
  14343. }
  14344. return this.parent.isSynchronized();
  14345. };
  14346. Node.prototype.isSynchronized = function (updateCache) {
  14347. var check = this.hasNewParent();
  14348. check = check || !this.isSynchronizedWithParent();
  14349. check = check || !this._isSynchronized();
  14350. if (updateCache)
  14351. this.updateCache(true);
  14352. return !check;
  14353. };
  14354. Node.prototype.hasNewParent = function (update) {
  14355. if (this._cache.parent === this.parent)
  14356. return false;
  14357. if (update)
  14358. this._cache.parent = this.parent;
  14359. return true;
  14360. };
  14361. /**
  14362. * Is this node ready to be used/rendered
  14363. * @return {boolean} is it ready
  14364. */
  14365. Node.prototype.isReady = function () {
  14366. return this._isReady;
  14367. };
  14368. /**
  14369. * Is this node enabled.
  14370. * 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.
  14371. * @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.
  14372. * @return {boolean} whether this node (and its parent) is enabled.
  14373. * @see setEnabled
  14374. */
  14375. Node.prototype.isEnabled = function (checkAncestors) {
  14376. if (checkAncestors === void 0) { checkAncestors = true; }
  14377. if (checkAncestors === false) {
  14378. return this._isEnabled;
  14379. }
  14380. if (this._isEnabled === false) {
  14381. return false;
  14382. }
  14383. if (this.parent !== undefined && this.parent !== null) {
  14384. return this.parent.isEnabled(checkAncestors);
  14385. }
  14386. return true;
  14387. };
  14388. /**
  14389. * Set the enabled state of this node.
  14390. * @param {boolean} value - the new enabled state
  14391. * @see isEnabled
  14392. */
  14393. Node.prototype.setEnabled = function (value) {
  14394. this._isEnabled = value;
  14395. };
  14396. /**
  14397. * Is this node a descendant of the given node.
  14398. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14399. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14400. * @see parent
  14401. */
  14402. Node.prototype.isDescendantOf = function (ancestor) {
  14403. if (this.parent) {
  14404. if (this.parent === ancestor) {
  14405. return true;
  14406. }
  14407. return this.parent.isDescendantOf(ancestor);
  14408. }
  14409. return false;
  14410. };
  14411. /**
  14412. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14413. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14414. * @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.
  14415. * @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.
  14416. */
  14417. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14418. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14419. if (!this._children) {
  14420. return;
  14421. }
  14422. for (var index = 0; index < this._children.length; index++) {
  14423. var item = this._children[index];
  14424. if (!predicate || predicate(item)) {
  14425. results.push(item);
  14426. }
  14427. if (!directDescendantsOnly) {
  14428. item._getDescendants(results, false, predicate);
  14429. }
  14430. }
  14431. };
  14432. /**
  14433. * Will return all nodes that have this node as ascendant.
  14434. * @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.
  14435. * @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.
  14436. * @return {BABYLON.Node[]} all children nodes of all types.
  14437. */
  14438. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14439. var results = new Array();
  14440. this._getDescendants(results, directDescendantsOnly, predicate);
  14441. return results;
  14442. };
  14443. /**
  14444. * Get all child-meshes of this node.
  14445. */
  14446. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14447. var results = [];
  14448. this._getDescendants(results, directDescendantsOnly, function (node) {
  14449. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14450. });
  14451. return results;
  14452. };
  14453. /**
  14454. * Get all child-transformNodes of this node.
  14455. */
  14456. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14457. var results = [];
  14458. this._getDescendants(results, directDescendantsOnly, function (node) {
  14459. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14460. });
  14461. return results;
  14462. };
  14463. /**
  14464. * Get all direct children of this node.
  14465. */
  14466. Node.prototype.getChildren = function (predicate) {
  14467. return this.getDescendants(true, predicate);
  14468. };
  14469. Node.prototype._setReady = function (state) {
  14470. if (state === this._isReady) {
  14471. return;
  14472. }
  14473. if (!state) {
  14474. this._isReady = false;
  14475. return;
  14476. }
  14477. this._isReady = true;
  14478. if (this.onReady) {
  14479. this.onReady(this);
  14480. }
  14481. };
  14482. Node.prototype.getAnimationByName = function (name) {
  14483. for (var i = 0; i < this.animations.length; i++) {
  14484. var animation = this.animations[i];
  14485. if (animation.name === name) {
  14486. return animation;
  14487. }
  14488. }
  14489. return null;
  14490. };
  14491. Node.prototype.createAnimationRange = function (name, from, to) {
  14492. // check name not already in use
  14493. if (!this._ranges[name]) {
  14494. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14495. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14496. if (this.animations[i]) {
  14497. this.animations[i].createRange(name, from, to);
  14498. }
  14499. }
  14500. }
  14501. };
  14502. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14503. if (deleteFrames === void 0) { deleteFrames = true; }
  14504. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14505. if (this.animations[i]) {
  14506. this.animations[i].deleteRange(name, deleteFrames);
  14507. }
  14508. }
  14509. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14510. };
  14511. Node.prototype.getAnimationRange = function (name) {
  14512. return this._ranges[name];
  14513. };
  14514. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14515. var range = this.getAnimationRange(name);
  14516. if (!range) {
  14517. return;
  14518. }
  14519. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14520. };
  14521. Node.prototype.serializeAnimationRanges = function () {
  14522. var serializationRanges = [];
  14523. for (var name in this._ranges) {
  14524. var localRange = this._ranges[name];
  14525. if (!localRange) {
  14526. continue;
  14527. }
  14528. var range = {};
  14529. range.name = name;
  14530. range.from = localRange.from;
  14531. range.to = localRange.to;
  14532. serializationRanges.push(range);
  14533. }
  14534. return serializationRanges;
  14535. };
  14536. // override it in derived class
  14537. Node.prototype.computeWorldMatrix = function (force) {
  14538. return BABYLON.Matrix.Identity();
  14539. };
  14540. Node.prototype.dispose = function () {
  14541. this.parent = null;
  14542. // Callback
  14543. this.onDisposeObservable.notifyObservers(this);
  14544. this.onDisposeObservable.clear();
  14545. // Behaviors
  14546. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14547. var behavior = _a[_i];
  14548. behavior.detach();
  14549. }
  14550. this._behaviors = [];
  14551. };
  14552. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14553. if (parsedNode.ranges) {
  14554. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14555. var data = parsedNode.ranges[index];
  14556. node.createAnimationRange(data.name, data.from, data.to);
  14557. }
  14558. }
  14559. };
  14560. __decorate([
  14561. BABYLON.serialize()
  14562. ], Node.prototype, "name", void 0);
  14563. __decorate([
  14564. BABYLON.serialize()
  14565. ], Node.prototype, "id", void 0);
  14566. __decorate([
  14567. BABYLON.serialize()
  14568. ], Node.prototype, "uniqueId", void 0);
  14569. __decorate([
  14570. BABYLON.serialize()
  14571. ], Node.prototype, "state", void 0);
  14572. __decorate([
  14573. BABYLON.serialize()
  14574. ], Node.prototype, "metadata", void 0);
  14575. return Node;
  14576. }());
  14577. BABYLON.Node = Node;
  14578. })(BABYLON || (BABYLON = {}));
  14579. //# sourceMappingURL=babylon.node.js.map
  14580. var BABYLON;
  14581. (function (BABYLON) {
  14582. var BoundingSphere = /** @class */ (function () {
  14583. function BoundingSphere(minimum, maximum) {
  14584. this.minimum = minimum;
  14585. this.maximum = maximum;
  14586. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14587. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14588. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14589. this.radius = distance * 0.5;
  14590. this.centerWorld = BABYLON.Vector3.Zero();
  14591. this._update(BABYLON.Matrix.Identity());
  14592. }
  14593. // Methods
  14594. BoundingSphere.prototype._update = function (world) {
  14595. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14596. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14597. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14598. };
  14599. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14600. for (var i = 0; i < 6; i++) {
  14601. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14602. return false;
  14603. }
  14604. return true;
  14605. };
  14606. BoundingSphere.prototype.intersectsPoint = function (point) {
  14607. var x = this.centerWorld.x - point.x;
  14608. var y = this.centerWorld.y - point.y;
  14609. var z = this.centerWorld.z - point.z;
  14610. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14611. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14612. return false;
  14613. return true;
  14614. };
  14615. // Statics
  14616. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14617. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14618. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14619. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14620. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14621. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14622. return false;
  14623. return true;
  14624. };
  14625. return BoundingSphere;
  14626. }());
  14627. BABYLON.BoundingSphere = BoundingSphere;
  14628. })(BABYLON || (BABYLON = {}));
  14629. //# sourceMappingURL=babylon.boundingSphere.js.map
  14630. var BABYLON;
  14631. (function (BABYLON) {
  14632. var BoundingBox = /** @class */ (function () {
  14633. function BoundingBox(minimum, maximum) {
  14634. this.minimum = minimum;
  14635. this.maximum = maximum;
  14636. this.vectors = new Array();
  14637. this.vectorsWorld = new Array();
  14638. // Bounding vectors
  14639. this.vectors.push(this.minimum.clone());
  14640. this.vectors.push(this.maximum.clone());
  14641. this.vectors.push(this.minimum.clone());
  14642. this.vectors[2].x = this.maximum.x;
  14643. this.vectors.push(this.minimum.clone());
  14644. this.vectors[3].y = this.maximum.y;
  14645. this.vectors.push(this.minimum.clone());
  14646. this.vectors[4].z = this.maximum.z;
  14647. this.vectors.push(this.maximum.clone());
  14648. this.vectors[5].z = this.minimum.z;
  14649. this.vectors.push(this.maximum.clone());
  14650. this.vectors[6].x = this.minimum.x;
  14651. this.vectors.push(this.maximum.clone());
  14652. this.vectors[7].y = this.minimum.y;
  14653. // OBB
  14654. this.center = this.maximum.add(this.minimum).scale(0.5);
  14655. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14656. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14657. // World
  14658. for (var index = 0; index < this.vectors.length; index++) {
  14659. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14660. }
  14661. this.minimumWorld = BABYLON.Vector3.Zero();
  14662. this.maximumWorld = BABYLON.Vector3.Zero();
  14663. this.centerWorld = BABYLON.Vector3.Zero();
  14664. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14665. this._update(BABYLON.Matrix.Identity());
  14666. }
  14667. // Methods
  14668. BoundingBox.prototype.getWorldMatrix = function () {
  14669. return this._worldMatrix;
  14670. };
  14671. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14672. this._worldMatrix.copyFrom(matrix);
  14673. return this;
  14674. };
  14675. BoundingBox.prototype._update = function (world) {
  14676. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14677. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14678. for (var index = 0; index < this.vectors.length; index++) {
  14679. var v = this.vectorsWorld[index];
  14680. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14681. if (v.x < this.minimumWorld.x)
  14682. this.minimumWorld.x = v.x;
  14683. if (v.y < this.minimumWorld.y)
  14684. this.minimumWorld.y = v.y;
  14685. if (v.z < this.minimumWorld.z)
  14686. this.minimumWorld.z = v.z;
  14687. if (v.x > this.maximumWorld.x)
  14688. this.maximumWorld.x = v.x;
  14689. if (v.y > this.maximumWorld.y)
  14690. this.maximumWorld.y = v.y;
  14691. if (v.z > this.maximumWorld.z)
  14692. this.maximumWorld.z = v.z;
  14693. }
  14694. // Extend
  14695. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14696. this.extendSizeWorld.scaleInPlace(0.5);
  14697. // OBB
  14698. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14699. this.centerWorld.scaleInPlace(0.5);
  14700. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14701. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14702. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14703. this._worldMatrix = world;
  14704. };
  14705. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14706. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14707. };
  14708. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14709. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14710. };
  14711. BoundingBox.prototype.intersectsPoint = function (point) {
  14712. var delta = -BABYLON.Epsilon;
  14713. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14714. return false;
  14715. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14716. return false;
  14717. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14718. return false;
  14719. return true;
  14720. };
  14721. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14722. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14723. };
  14724. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14725. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14726. return false;
  14727. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14728. return false;
  14729. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14730. return false;
  14731. return true;
  14732. };
  14733. // Statics
  14734. BoundingBox.Intersects = function (box0, box1) {
  14735. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14736. return false;
  14737. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14738. return false;
  14739. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14740. return false;
  14741. return true;
  14742. };
  14743. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14744. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14745. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14746. return (num <= (sphereRadius * sphereRadius));
  14747. };
  14748. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14749. for (var p = 0; p < 6; p++) {
  14750. for (var i = 0; i < 8; i++) {
  14751. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14752. return false;
  14753. }
  14754. }
  14755. }
  14756. return true;
  14757. };
  14758. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14759. for (var p = 0; p < 6; p++) {
  14760. var inCount = 8;
  14761. for (var i = 0; i < 8; i++) {
  14762. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14763. --inCount;
  14764. }
  14765. else {
  14766. break;
  14767. }
  14768. }
  14769. if (inCount === 0)
  14770. return false;
  14771. }
  14772. return true;
  14773. };
  14774. return BoundingBox;
  14775. }());
  14776. BABYLON.BoundingBox = BoundingBox;
  14777. })(BABYLON || (BABYLON = {}));
  14778. //# sourceMappingURL=babylon.boundingBox.js.map
  14779. var BABYLON;
  14780. (function (BABYLON) {
  14781. var computeBoxExtents = function (axis, box) {
  14782. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14783. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14784. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14785. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14786. var r = r0 + r1 + r2;
  14787. return {
  14788. min: p - r,
  14789. max: p + r
  14790. };
  14791. };
  14792. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14793. var axisOverlap = function (axis, box0, box1) {
  14794. var result0 = computeBoxExtents(axis, box0);
  14795. var result1 = computeBoxExtents(axis, box1);
  14796. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14797. };
  14798. var BoundingInfo = /** @class */ (function () {
  14799. function BoundingInfo(minimum, maximum) {
  14800. this.minimum = minimum;
  14801. this.maximum = maximum;
  14802. this._isLocked = false;
  14803. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14804. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14805. }
  14806. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14807. get: function () {
  14808. return this._isLocked;
  14809. },
  14810. set: function (value) {
  14811. this._isLocked = value;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. // Methods
  14817. BoundingInfo.prototype.update = function (world) {
  14818. if (this._isLocked) {
  14819. return;
  14820. }
  14821. this.boundingBox._update(world);
  14822. this.boundingSphere._update(world);
  14823. };
  14824. /**
  14825. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14826. * @param center New center of the bounding info
  14827. * @param extend New extend of the bounding info
  14828. */
  14829. BoundingInfo.prototype.centerOn = function (center, extend) {
  14830. this.minimum = center.subtract(extend);
  14831. this.maximum = center.add(extend);
  14832. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14833. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14834. return this;
  14835. };
  14836. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14837. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14838. return false;
  14839. return this.boundingBox.isInFrustum(frustumPlanes);
  14840. };
  14841. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14842. /**
  14843. * Gets the world distance between the min and max points of the bounding box
  14844. */
  14845. get: function () {
  14846. var boundingBox = this.boundingBox;
  14847. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14848. return size.length();
  14849. },
  14850. enumerable: true,
  14851. configurable: true
  14852. });
  14853. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14854. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14855. };
  14856. BoundingInfo.prototype._checkCollision = function (collider) {
  14857. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14858. };
  14859. BoundingInfo.prototype.intersectsPoint = function (point) {
  14860. if (!this.boundingSphere.centerWorld) {
  14861. return false;
  14862. }
  14863. if (!this.boundingSphere.intersectsPoint(point)) {
  14864. return false;
  14865. }
  14866. if (!this.boundingBox.intersectsPoint(point)) {
  14867. return false;
  14868. }
  14869. return true;
  14870. };
  14871. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14872. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14873. return false;
  14874. }
  14875. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14876. return false;
  14877. }
  14878. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14879. return false;
  14880. }
  14881. if (!precise) {
  14882. return true;
  14883. }
  14884. var box0 = this.boundingBox;
  14885. var box1 = boundingInfo.boundingBox;
  14886. if (!axisOverlap(box0.directions[0], box0, box1))
  14887. return false;
  14888. if (!axisOverlap(box0.directions[1], box0, box1))
  14889. return false;
  14890. if (!axisOverlap(box0.directions[2], box0, box1))
  14891. return false;
  14892. if (!axisOverlap(box1.directions[0], box0, box1))
  14893. return false;
  14894. if (!axisOverlap(box1.directions[1], box0, box1))
  14895. return false;
  14896. if (!axisOverlap(box1.directions[2], box0, box1))
  14897. return false;
  14898. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14899. return false;
  14900. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14901. return false;
  14902. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14903. return false;
  14904. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14905. return false;
  14906. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14907. return false;
  14908. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14909. return false;
  14910. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14911. return false;
  14912. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14913. return false;
  14914. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14915. return false;
  14916. return true;
  14917. };
  14918. return BoundingInfo;
  14919. }());
  14920. BABYLON.BoundingInfo = BoundingInfo;
  14921. })(BABYLON || (BABYLON = {}));
  14922. //# sourceMappingURL=babylon.boundingInfo.js.map
  14923. var BABYLON;
  14924. (function (BABYLON) {
  14925. var TransformNode = /** @class */ (function (_super) {
  14926. __extends(TransformNode, _super);
  14927. function TransformNode(name, scene, isPure) {
  14928. if (scene === void 0) { scene = null; }
  14929. if (isPure === void 0) { isPure = true; }
  14930. var _this = _super.call(this, name, scene) || this;
  14931. // Properties
  14932. _this._rotation = BABYLON.Vector3.Zero();
  14933. _this._scaling = BABYLON.Vector3.One();
  14934. _this._isDirty = false;
  14935. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14936. _this.scalingDeterminant = 1;
  14937. _this.infiniteDistance = false;
  14938. _this.position = BABYLON.Vector3.Zero();
  14939. _this._localWorld = BABYLON.Matrix.Zero();
  14940. _this._worldMatrix = BABYLON.Matrix.Zero();
  14941. _this._worldMatrixDeterminant = 0;
  14942. _this._absolutePosition = BABYLON.Vector3.Zero();
  14943. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14944. _this._postMultiplyPivotMatrix = false;
  14945. _this._isWorldMatrixFrozen = false;
  14946. /**
  14947. * An event triggered after the world matrix is updated
  14948. * @type {BABYLON.Observable}
  14949. */
  14950. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14951. _this._nonUniformScaling = false;
  14952. if (isPure) {
  14953. _this.getScene().addTransformNode(_this);
  14954. }
  14955. return _this;
  14956. }
  14957. Object.defineProperty(TransformNode.prototype, "rotation", {
  14958. /**
  14959. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14960. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14961. * Default : (0.0, 0.0, 0.0)
  14962. */
  14963. get: function () {
  14964. return this._rotation;
  14965. },
  14966. set: function (newRotation) {
  14967. this._rotation = newRotation;
  14968. },
  14969. enumerable: true,
  14970. configurable: true
  14971. });
  14972. Object.defineProperty(TransformNode.prototype, "scaling", {
  14973. /**
  14974. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14975. * Default : (1.0, 1.0, 1.0)
  14976. */
  14977. get: function () {
  14978. return this._scaling;
  14979. },
  14980. /**
  14981. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14982. * Default : (1.0, 1.0, 1.0)
  14983. */
  14984. set: function (newScaling) {
  14985. this._scaling = newScaling;
  14986. },
  14987. enumerable: true,
  14988. configurable: true
  14989. });
  14990. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14991. /**
  14992. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14993. * It's null by default.
  14994. * 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)
  14995. */
  14996. get: function () {
  14997. return this._rotationQuaternion;
  14998. },
  14999. set: function (quaternion) {
  15000. this._rotationQuaternion = quaternion;
  15001. //reset the rotation vector.
  15002. if (quaternion && this.rotation.length()) {
  15003. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15004. }
  15005. },
  15006. enumerable: true,
  15007. configurable: true
  15008. });
  15009. /**
  15010. * Returns the latest update of the World matrix
  15011. * Returns a Matrix.
  15012. */
  15013. TransformNode.prototype.getWorldMatrix = function () {
  15014. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15015. this.computeWorldMatrix();
  15016. }
  15017. return this._worldMatrix;
  15018. };
  15019. /**
  15020. * Returns the latest update of the World matrix determinant.
  15021. */
  15022. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15023. return this._worldMatrixDeterminant;
  15024. };
  15025. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15026. /**
  15027. * Returns directly the latest state of the mesh World matrix.
  15028. * A Matrix is returned.
  15029. */
  15030. get: function () {
  15031. return this._worldMatrix;
  15032. },
  15033. enumerable: true,
  15034. configurable: true
  15035. });
  15036. /**
  15037. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15038. * Returns the AbstractMesh.
  15039. */
  15040. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15041. this._poseMatrix.copyFrom(matrix);
  15042. return this;
  15043. };
  15044. /**
  15045. * Returns the mesh Pose matrix.
  15046. * Returned object : Matrix
  15047. */
  15048. TransformNode.prototype.getPoseMatrix = function () {
  15049. return this._poseMatrix;
  15050. };
  15051. TransformNode.prototype._isSynchronized = function () {
  15052. if (this._isDirty) {
  15053. return false;
  15054. }
  15055. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15056. return false;
  15057. if (this._cache.pivotMatrixUpdated) {
  15058. return false;
  15059. }
  15060. if (this.infiniteDistance) {
  15061. return false;
  15062. }
  15063. if (!this._cache.position.equals(this.position))
  15064. return false;
  15065. if (this.rotationQuaternion) {
  15066. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15067. return false;
  15068. }
  15069. if (!this._cache.rotation.equals(this.rotation))
  15070. return false;
  15071. if (!this._cache.scaling.equals(this.scaling))
  15072. return false;
  15073. return true;
  15074. };
  15075. TransformNode.prototype._initCache = function () {
  15076. _super.prototype._initCache.call(this);
  15077. this._cache.localMatrixUpdated = false;
  15078. this._cache.position = BABYLON.Vector3.Zero();
  15079. this._cache.scaling = BABYLON.Vector3.Zero();
  15080. this._cache.rotation = BABYLON.Vector3.Zero();
  15081. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15082. this._cache.billboardMode = -1;
  15083. };
  15084. TransformNode.prototype.markAsDirty = function (property) {
  15085. if (property === "rotation") {
  15086. this.rotationQuaternion = null;
  15087. }
  15088. this._currentRenderId = Number.MAX_VALUE;
  15089. this._isDirty = true;
  15090. return this;
  15091. };
  15092. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15093. /**
  15094. * Returns the current mesh absolute position.
  15095. * Retuns a Vector3.
  15096. */
  15097. get: function () {
  15098. return this._absolutePosition;
  15099. },
  15100. enumerable: true,
  15101. configurable: true
  15102. });
  15103. /**
  15104. * Sets a new pivot matrix to the mesh.
  15105. * Returns the AbstractMesh.
  15106. */
  15107. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15108. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  15109. this._pivotMatrix = matrix.clone();
  15110. this._cache.pivotMatrixUpdated = true;
  15111. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15112. if (this._postMultiplyPivotMatrix) {
  15113. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  15114. }
  15115. return this;
  15116. };
  15117. /**
  15118. * Returns the mesh pivot matrix.
  15119. * Default : Identity.
  15120. * A Matrix is returned.
  15121. */
  15122. TransformNode.prototype.getPivotMatrix = function () {
  15123. return this._pivotMatrix;
  15124. };
  15125. /**
  15126. * Prevents the World matrix to be computed any longer.
  15127. * Returns the AbstractMesh.
  15128. */
  15129. TransformNode.prototype.freezeWorldMatrix = function () {
  15130. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15131. this.computeWorldMatrix(true);
  15132. this._isWorldMatrixFrozen = true;
  15133. return this;
  15134. };
  15135. /**
  15136. * Allows back the World matrix computation.
  15137. * Returns the AbstractMesh.
  15138. */
  15139. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15140. this._isWorldMatrixFrozen = false;
  15141. this.computeWorldMatrix(true);
  15142. return this;
  15143. };
  15144. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15145. /**
  15146. * True if the World matrix has been frozen.
  15147. * Returns a boolean.
  15148. */
  15149. get: function () {
  15150. return this._isWorldMatrixFrozen;
  15151. },
  15152. enumerable: true,
  15153. configurable: true
  15154. });
  15155. /**
  15156. * Retuns the mesh absolute position in the World.
  15157. * Returns a Vector3.
  15158. */
  15159. TransformNode.prototype.getAbsolutePosition = function () {
  15160. this.computeWorldMatrix();
  15161. return this._absolutePosition;
  15162. };
  15163. /**
  15164. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15165. * Returns the AbstractMesh.
  15166. */
  15167. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15168. if (!absolutePosition) {
  15169. return this;
  15170. }
  15171. var absolutePositionX;
  15172. var absolutePositionY;
  15173. var absolutePositionZ;
  15174. if (absolutePosition.x === undefined) {
  15175. if (arguments.length < 3) {
  15176. return this;
  15177. }
  15178. absolutePositionX = arguments[0];
  15179. absolutePositionY = arguments[1];
  15180. absolutePositionZ = arguments[2];
  15181. }
  15182. else {
  15183. absolutePositionX = absolutePosition.x;
  15184. absolutePositionY = absolutePosition.y;
  15185. absolutePositionZ = absolutePosition.z;
  15186. }
  15187. if (this.parent) {
  15188. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15189. invertParentWorldMatrix.invert();
  15190. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15191. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15192. }
  15193. else {
  15194. this.position.x = absolutePositionX;
  15195. this.position.y = absolutePositionY;
  15196. this.position.z = absolutePositionZ;
  15197. }
  15198. return this;
  15199. };
  15200. /**
  15201. * Sets the mesh position in its local space.
  15202. * Returns the AbstractMesh.
  15203. */
  15204. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15205. this.computeWorldMatrix();
  15206. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15207. return this;
  15208. };
  15209. /**
  15210. * Returns the mesh position in the local space from the current World matrix values.
  15211. * Returns a new Vector3.
  15212. */
  15213. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15214. this.computeWorldMatrix();
  15215. var invLocalWorldMatrix = this._localWorld.clone();
  15216. invLocalWorldMatrix.invert();
  15217. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15218. };
  15219. /**
  15220. * Translates the mesh along the passed Vector3 in its local space.
  15221. * Returns the AbstractMesh.
  15222. */
  15223. TransformNode.prototype.locallyTranslate = function (vector3) {
  15224. this.computeWorldMatrix(true);
  15225. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15226. return this;
  15227. };
  15228. /**
  15229. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15230. * @param targetPoint the position (must be in same space as current mesh) to look at
  15231. * @param yawCor optional yaw (y-axis) correction in radians
  15232. * @param pitchCor optional pitch (x-axis) correction in radians
  15233. * @param rollCor optional roll (z-axis) correction in radians
  15234. * @param space the choosen space of the target
  15235. * @returns the TransformNode.
  15236. */
  15237. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15238. if (yawCor === void 0) { yawCor = 0; }
  15239. if (pitchCor === void 0) { pitchCor = 0; }
  15240. if (rollCor === void 0) { rollCor = 0; }
  15241. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15242. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15243. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15244. targetPoint.subtractToRef(pos, dv);
  15245. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15246. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15247. var pitch = Math.atan2(dv.y, len);
  15248. if (this.rotationQuaternion) {
  15249. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15250. }
  15251. else {
  15252. this.rotation.x = pitch + pitchCor;
  15253. this.rotation.y = yaw + yawCor;
  15254. this.rotation.z = rollCor;
  15255. }
  15256. return this;
  15257. };
  15258. /**
  15259. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15260. * This Vector3 is expressed in the World space.
  15261. */
  15262. TransformNode.prototype.getDirection = function (localAxis) {
  15263. var result = BABYLON.Vector3.Zero();
  15264. this.getDirectionToRef(localAxis, result);
  15265. return result;
  15266. };
  15267. /**
  15268. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15269. * localAxis is expressed in the mesh local space.
  15270. * result is computed in the Wordl space from the mesh World matrix.
  15271. * Returns the AbstractMesh.
  15272. */
  15273. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15274. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15275. return this;
  15276. };
  15277. TransformNode.prototype.setPivotPoint = function (point, space) {
  15278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15279. if (this.getScene().getRenderId() == 0) {
  15280. this.computeWorldMatrix(true);
  15281. }
  15282. var wm = this.getWorldMatrix();
  15283. if (space == BABYLON.Space.WORLD) {
  15284. var tmat = BABYLON.Tmp.Matrix[0];
  15285. wm.invertToRef(tmat);
  15286. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15287. }
  15288. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15289. this._pivotMatrix.m[12] = -point.x;
  15290. this._pivotMatrix.m[13] = -point.y;
  15291. this._pivotMatrix.m[14] = -point.z;
  15292. this._cache.pivotMatrixUpdated = true;
  15293. return this;
  15294. };
  15295. /**
  15296. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15297. */
  15298. TransformNode.prototype.getPivotPoint = function () {
  15299. var point = BABYLON.Vector3.Zero();
  15300. this.getPivotPointToRef(point);
  15301. return point;
  15302. };
  15303. /**
  15304. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15305. * Returns the AbstractMesh.
  15306. */
  15307. TransformNode.prototype.getPivotPointToRef = function (result) {
  15308. result.x = -this._pivotMatrix.m[12];
  15309. result.y = -this._pivotMatrix.m[13];
  15310. result.z = -this._pivotMatrix.m[14];
  15311. return this;
  15312. };
  15313. /**
  15314. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15315. */
  15316. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15317. var point = BABYLON.Vector3.Zero();
  15318. this.getAbsolutePivotPointToRef(point);
  15319. return point;
  15320. };
  15321. /**
  15322. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15323. * Returns the AbstractMesh.
  15324. */
  15325. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15326. result.x = this._pivotMatrix.m[12];
  15327. result.y = this._pivotMatrix.m[13];
  15328. result.z = this._pivotMatrix.m[14];
  15329. this.getPivotPointToRef(result);
  15330. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15331. return this;
  15332. };
  15333. /**
  15334. * Defines the passed node as the parent of the current node.
  15335. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15336. * Returns the TransformNode.
  15337. */
  15338. TransformNode.prototype.setParent = function (node) {
  15339. if (node === null) {
  15340. var rotation = BABYLON.Tmp.Quaternion[0];
  15341. var position = BABYLON.Tmp.Vector3[0];
  15342. var scale = BABYLON.Tmp.Vector3[1];
  15343. if (this.parent && this.parent.computeWorldMatrix) {
  15344. this.parent.computeWorldMatrix(true);
  15345. }
  15346. this.computeWorldMatrix(true);
  15347. this.getWorldMatrix().decompose(scale, rotation, position);
  15348. if (this.rotationQuaternion) {
  15349. this.rotationQuaternion.copyFrom(rotation);
  15350. }
  15351. else {
  15352. rotation.toEulerAnglesToRef(this.rotation);
  15353. }
  15354. this.scaling.x = scale.x;
  15355. this.scaling.y = scale.y;
  15356. this.scaling.z = scale.z;
  15357. this.position.x = position.x;
  15358. this.position.y = position.y;
  15359. this.position.z = position.z;
  15360. }
  15361. else {
  15362. var rotation = BABYLON.Tmp.Quaternion[0];
  15363. var position = BABYLON.Tmp.Vector3[0];
  15364. var scale = BABYLON.Tmp.Vector3[1];
  15365. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15366. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15367. this.computeWorldMatrix(true);
  15368. node.computeWorldMatrix(true);
  15369. node.getWorldMatrix().invertToRef(invParentMatrix);
  15370. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15371. diffMatrix.decompose(scale, rotation, position);
  15372. if (this.rotationQuaternion) {
  15373. this.rotationQuaternion.copyFrom(rotation);
  15374. }
  15375. else {
  15376. rotation.toEulerAnglesToRef(this.rotation);
  15377. }
  15378. this.position.x = position.x;
  15379. this.position.y = position.y;
  15380. this.position.z = position.z;
  15381. this.scaling.x = scale.x;
  15382. this.scaling.y = scale.y;
  15383. this.scaling.z = scale.z;
  15384. }
  15385. this.parent = node;
  15386. return this;
  15387. };
  15388. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15389. get: function () {
  15390. return this._nonUniformScaling;
  15391. },
  15392. enumerable: true,
  15393. configurable: true
  15394. });
  15395. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15396. if (this._nonUniformScaling === value) {
  15397. return false;
  15398. }
  15399. this._nonUniformScaling = true;
  15400. return true;
  15401. };
  15402. /**
  15403. * Attach the current TransformNode to another TransformNode associated with a bone
  15404. * @param bone Bone affecting the TransformNode
  15405. * @param affectedTransformNode TransformNode associated with the bone
  15406. */
  15407. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15408. this._transformToBoneReferal = affectedTransformNode;
  15409. this.parent = bone;
  15410. if (bone.getWorldMatrix().determinant() < 0) {
  15411. this.scalingDeterminant *= -1;
  15412. }
  15413. return this;
  15414. };
  15415. TransformNode.prototype.detachFromBone = function () {
  15416. if (!this.parent) {
  15417. return this;
  15418. }
  15419. if (this.parent.getWorldMatrix().determinant() < 0) {
  15420. this.scalingDeterminant *= -1;
  15421. }
  15422. this._transformToBoneReferal = null;
  15423. this.parent = null;
  15424. return this;
  15425. };
  15426. /**
  15427. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15428. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15429. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15430. * The passed axis is also normalized.
  15431. * Returns the AbstractMesh.
  15432. */
  15433. TransformNode.prototype.rotate = function (axis, amount, space) {
  15434. axis.normalize();
  15435. if (!this.rotationQuaternion) {
  15436. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15437. this.rotation = BABYLON.Vector3.Zero();
  15438. }
  15439. var rotationQuaternion;
  15440. if (!space || space === BABYLON.Space.LOCAL) {
  15441. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15442. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15443. }
  15444. else {
  15445. if (this.parent) {
  15446. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15447. invertParentWorldMatrix.invert();
  15448. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15449. }
  15450. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15451. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15452. }
  15453. return this;
  15454. };
  15455. /**
  15456. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15457. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15458. * The passed axis is also normalized.
  15459. * Returns the AbstractMesh.
  15460. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15461. */
  15462. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15463. axis.normalize();
  15464. if (!this.rotationQuaternion) {
  15465. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15466. this.rotation.copyFromFloats(0, 0, 0);
  15467. }
  15468. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15469. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15470. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15471. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15472. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15473. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15474. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15475. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15476. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15477. return this;
  15478. };
  15479. /**
  15480. * Translates the mesh along the axis vector for the passed distance in the given space.
  15481. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15482. * Returns the AbstractMesh.
  15483. */
  15484. TransformNode.prototype.translate = function (axis, distance, space) {
  15485. var displacementVector = axis.scale(distance);
  15486. if (!space || space === BABYLON.Space.LOCAL) {
  15487. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15488. this.setPositionWithLocalVector(tempV3);
  15489. }
  15490. else {
  15491. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15492. }
  15493. return this;
  15494. };
  15495. /**
  15496. * Adds a rotation step to the mesh current rotation.
  15497. * x, y, z are Euler angles expressed in radians.
  15498. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15499. * This means this rotation is made in the mesh local space only.
  15500. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15501. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15502. * ```javascript
  15503. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15504. * ```
  15505. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15506. * 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.
  15507. * Returns the AbstractMesh.
  15508. */
  15509. TransformNode.prototype.addRotation = function (x, y, z) {
  15510. var rotationQuaternion;
  15511. if (this.rotationQuaternion) {
  15512. rotationQuaternion = this.rotationQuaternion;
  15513. }
  15514. else {
  15515. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15516. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15517. }
  15518. var accumulation = BABYLON.Tmp.Quaternion[0];
  15519. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15520. rotationQuaternion.multiplyInPlace(accumulation);
  15521. if (!this.rotationQuaternion) {
  15522. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15523. }
  15524. return this;
  15525. };
  15526. /**
  15527. * Computes the mesh World matrix and returns it.
  15528. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15529. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15530. * If the parameter `force`is set to `true`, the actual computation is done.
  15531. * Returns the mesh World Matrix.
  15532. */
  15533. TransformNode.prototype.computeWorldMatrix = function (force) {
  15534. if (this._isWorldMatrixFrozen) {
  15535. return this._worldMatrix;
  15536. }
  15537. if (!force && this.isSynchronized(true)) {
  15538. return this._worldMatrix;
  15539. }
  15540. this._cache.position.copyFrom(this.position);
  15541. this._cache.scaling.copyFrom(this.scaling);
  15542. this._cache.pivotMatrixUpdated = false;
  15543. this._cache.billboardMode = this.billboardMode;
  15544. this._currentRenderId = this.getScene().getRenderId();
  15545. this._isDirty = false;
  15546. // Scaling
  15547. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15548. // Rotation
  15549. //rotate, if quaternion is set and rotation was used
  15550. if (this.rotationQuaternion) {
  15551. var len = this.rotation.length();
  15552. if (len) {
  15553. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15554. this.rotation.copyFromFloats(0, 0, 0);
  15555. }
  15556. }
  15557. if (this.rotationQuaternion) {
  15558. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15559. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15560. }
  15561. else {
  15562. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15563. this._cache.rotation.copyFrom(this.rotation);
  15564. }
  15565. // Translation
  15566. var camera = this.getScene().activeCamera;
  15567. if (this.infiniteDistance && !this.parent && camera) {
  15568. var cameraWorldMatrix = camera.getWorldMatrix();
  15569. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15570. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15571. }
  15572. else {
  15573. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15574. }
  15575. // Composing transformations
  15576. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15577. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15578. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15579. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15580. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15581. // Need to decompose each rotation here
  15582. var currentPosition = BABYLON.Tmp.Vector3[3];
  15583. if (this.parent && this.parent.getWorldMatrix) {
  15584. if (this._transformToBoneReferal) {
  15585. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15586. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15587. }
  15588. else {
  15589. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15590. }
  15591. }
  15592. else {
  15593. currentPosition.copyFrom(this.position);
  15594. }
  15595. currentPosition.subtractInPlace(camera.globalPosition);
  15596. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15597. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15598. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15599. }
  15600. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15601. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15602. }
  15603. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15604. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15605. }
  15606. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15607. }
  15608. else {
  15609. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15610. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15611. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15612. }
  15613. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15614. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15615. }
  15616. // Local world
  15617. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15618. // Parent
  15619. if (this.parent && this.parent.getWorldMatrix) {
  15620. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15621. if (this._transformToBoneReferal) {
  15622. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15623. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15624. }
  15625. else {
  15626. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15627. }
  15628. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15629. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15630. this._worldMatrix.copyFrom(this._localWorld);
  15631. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15632. }
  15633. else {
  15634. if (this._transformToBoneReferal) {
  15635. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15636. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15637. }
  15638. else {
  15639. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15640. }
  15641. }
  15642. this._markSyncedWithParent();
  15643. }
  15644. else {
  15645. this._worldMatrix.copyFrom(this._localWorld);
  15646. }
  15647. // Post multiply inverse of pivotMatrix
  15648. if (this._postMultiplyPivotMatrix) {
  15649. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15650. }
  15651. // Normal matrix
  15652. if (this.scaling.isNonUniform) {
  15653. this._updateNonUniformScalingState(true);
  15654. }
  15655. else if (this.parent && this.parent._nonUniformScaling) {
  15656. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15657. }
  15658. else {
  15659. this._updateNonUniformScalingState(false);
  15660. }
  15661. this._afterComputeWorldMatrix();
  15662. // Absolute position
  15663. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15664. // Callbacks
  15665. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15666. if (!this._poseMatrix) {
  15667. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15668. }
  15669. // Cache the determinant
  15670. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15671. return this._worldMatrix;
  15672. };
  15673. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15674. };
  15675. /**
  15676. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15677. * @param func: callback function to add
  15678. *
  15679. * Returns the TransformNode.
  15680. */
  15681. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15682. this.onAfterWorldMatrixUpdateObservable.add(func);
  15683. return this;
  15684. };
  15685. /**
  15686. * Removes a registered callback function.
  15687. * Returns the TransformNode.
  15688. */
  15689. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15690. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15691. return this;
  15692. };
  15693. /**
  15694. * Clone the current transform node
  15695. * Returns the new transform node
  15696. * @param name Name of the new clone
  15697. * @param newParent New parent for the clone
  15698. * @param doNotCloneChildren Do not clone children hierarchy
  15699. */
  15700. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15701. var _this = this;
  15702. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15703. result.name = name;
  15704. result.id = name;
  15705. if (newParent) {
  15706. result.parent = newParent;
  15707. }
  15708. if (!doNotCloneChildren) {
  15709. // Children
  15710. var directDescendants = this.getDescendants(true);
  15711. for (var index = 0; index < directDescendants.length; index++) {
  15712. var child = directDescendants[index];
  15713. if (child.clone) {
  15714. child.clone(name + "." + child.name, result);
  15715. }
  15716. }
  15717. }
  15718. return result;
  15719. };
  15720. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15721. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15722. serializationObject.type = this.getClassName();
  15723. // Parent
  15724. if (this.parent) {
  15725. serializationObject.parentId = this.parent.id;
  15726. }
  15727. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15728. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15729. }
  15730. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15731. serializationObject.isEnabled = this.isEnabled();
  15732. // Parent
  15733. if (this.parent) {
  15734. serializationObject.parentId = this.parent.id;
  15735. }
  15736. return serializationObject;
  15737. };
  15738. // Statics
  15739. /**
  15740. * Returns a new TransformNode object parsed from the source provided.
  15741. * The parameter `parsedMesh` is the source.
  15742. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15743. */
  15744. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15745. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15746. if (BABYLON.Tags) {
  15747. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15748. }
  15749. if (parsedTransformNode.localMatrix) {
  15750. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15751. }
  15752. else if (parsedTransformNode.pivotMatrix) {
  15753. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15754. }
  15755. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15756. // Parent
  15757. if (parsedTransformNode.parentId) {
  15758. transformNode._waitingParentId = parsedTransformNode.parentId;
  15759. }
  15760. return transformNode;
  15761. };
  15762. /**
  15763. * Disposes the TransformNode.
  15764. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15765. * Returns nothing.
  15766. */
  15767. TransformNode.prototype.dispose = function (doNotRecurse) {
  15768. // Animations
  15769. this.getScene().stopAnimation(this);
  15770. // Remove from scene
  15771. this.getScene().removeTransformNode(this);
  15772. if (!doNotRecurse) {
  15773. // Children
  15774. var objects = this.getDescendants(true);
  15775. for (var index = 0; index < objects.length; index++) {
  15776. objects[index].dispose();
  15777. }
  15778. }
  15779. else {
  15780. var childMeshes = this.getChildMeshes(true);
  15781. for (index = 0; index < childMeshes.length; index++) {
  15782. var child = childMeshes[index];
  15783. child.parent = null;
  15784. child.computeWorldMatrix(true);
  15785. }
  15786. }
  15787. this.onAfterWorldMatrixUpdateObservable.clear();
  15788. _super.prototype.dispose.call(this);
  15789. };
  15790. // Statics
  15791. TransformNode.BILLBOARDMODE_NONE = 0;
  15792. TransformNode.BILLBOARDMODE_X = 1;
  15793. TransformNode.BILLBOARDMODE_Y = 2;
  15794. TransformNode.BILLBOARDMODE_Z = 4;
  15795. TransformNode.BILLBOARDMODE_ALL = 7;
  15796. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15797. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15798. __decorate([
  15799. BABYLON.serializeAsVector3()
  15800. ], TransformNode.prototype, "_rotation", void 0);
  15801. __decorate([
  15802. BABYLON.serializeAsQuaternion()
  15803. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15804. __decorate([
  15805. BABYLON.serializeAsVector3()
  15806. ], TransformNode.prototype, "_scaling", void 0);
  15807. __decorate([
  15808. BABYLON.serialize()
  15809. ], TransformNode.prototype, "billboardMode", void 0);
  15810. __decorate([
  15811. BABYLON.serialize()
  15812. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15813. __decorate([
  15814. BABYLON.serialize()
  15815. ], TransformNode.prototype, "infiniteDistance", void 0);
  15816. __decorate([
  15817. BABYLON.serializeAsVector3()
  15818. ], TransformNode.prototype, "position", void 0);
  15819. return TransformNode;
  15820. }(BABYLON.Node));
  15821. BABYLON.TransformNode = TransformNode;
  15822. })(BABYLON || (BABYLON = {}));
  15823. //# sourceMappingURL=babylon.transformNode.js.map
  15824. var BABYLON;
  15825. (function (BABYLON) {
  15826. var AbstractMesh = /** @class */ (function (_super) {
  15827. __extends(AbstractMesh, _super);
  15828. // Constructor
  15829. function AbstractMesh(name, scene) {
  15830. if (scene === void 0) { scene = null; }
  15831. var _this = _super.call(this, name, scene, false) || this;
  15832. _this._facetNb = 0; // facet number
  15833. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15834. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15835. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15836. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15837. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15838. _this._subDiv = {
  15839. max: 1,
  15840. X: 1,
  15841. Y: 1,
  15842. Z: 1
  15843. };
  15844. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15845. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15846. // Events
  15847. /**
  15848. * An event triggered when this mesh collides with another one
  15849. * @type {BABYLON.Observable}
  15850. */
  15851. _this.onCollideObservable = new BABYLON.Observable();
  15852. /**
  15853. * An event triggered when the collision's position changes
  15854. * @type {BABYLON.Observable}
  15855. */
  15856. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15857. /**
  15858. * An event triggered when material is changed
  15859. * @type {BABYLON.Observable}
  15860. */
  15861. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15862. // Properties
  15863. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15864. /**
  15865. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15866. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15867. * or
  15868. * 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.
  15869. * for more info check WebGl documentations
  15870. */
  15871. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15872. /**
  15873. * 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:
  15874. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15875. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15876. * 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.
  15877. */
  15878. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15879. /**
  15880. * 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.
  15881. * The default value is -1 which means don't break the query and wait till the result.
  15882. */
  15883. _this.occlusionRetryCount = -1;
  15884. _this._occlusionInternalRetryCounter = 0;
  15885. _this._isOccluded = false;
  15886. _this._isOcclusionQueryInProgress = false;
  15887. _this._visibility = 1.0;
  15888. _this.alphaIndex = Number.MAX_VALUE;
  15889. _this.isVisible = true;
  15890. _this.isPickable = true;
  15891. _this.showBoundingBox = false;
  15892. _this.showSubMeshesBoundingBox = false;
  15893. _this.isBlocker = false;
  15894. _this.enablePointerMoveEvents = false;
  15895. _this.renderingGroupId = 0;
  15896. _this._receiveShadows = false;
  15897. _this.renderOutline = false;
  15898. _this.outlineColor = BABYLON.Color3.Red();
  15899. _this.outlineWidth = 0.02;
  15900. _this.renderOverlay = false;
  15901. _this.overlayColor = BABYLON.Color3.Red();
  15902. _this.overlayAlpha = 0.5;
  15903. _this._hasVertexAlpha = false;
  15904. _this._useVertexColors = true;
  15905. _this._computeBonesUsingShaders = true;
  15906. _this._numBoneInfluencers = 4;
  15907. _this._applyFog = true;
  15908. _this.useOctreeForRenderingSelection = true;
  15909. _this.useOctreeForPicking = true;
  15910. _this.useOctreeForCollisions = true;
  15911. _this._layerMask = 0x0FFFFFFF;
  15912. /**
  15913. * True if the mesh must be rendered in any case.
  15914. */
  15915. _this.alwaysSelectAsActiveMesh = false;
  15916. /**
  15917. * This scene's action manager
  15918. * @type {BABYLON.ActionManager}
  15919. */
  15920. _this.actionManager = null;
  15921. // Physics
  15922. _this.physicsImpostor = null;
  15923. // Collisions
  15924. _this._checkCollisions = false;
  15925. _this._collisionMask = -1;
  15926. _this._collisionGroup = -1;
  15927. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15928. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15929. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15930. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15931. // Edges
  15932. _this.edgesWidth = 1;
  15933. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15934. // Cache
  15935. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15936. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15937. _this._isDisposed = false;
  15938. _this._renderId = 0;
  15939. _this._intersectionsInProgress = new Array();
  15940. _this._unIndexed = false;
  15941. _this._lightSources = new Array();
  15942. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15943. if (collidedMesh === void 0) { collidedMesh = null; }
  15944. //TODO move this to the collision coordinator!
  15945. if (_this.getScene().workerCollisions)
  15946. newPosition.multiplyInPlace(_this._collider._radius);
  15947. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15948. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15949. _this.position.addInPlace(_this._diffPositionForCollisions);
  15950. }
  15951. if (collidedMesh) {
  15952. _this.onCollideObservable.notifyObservers(collidedMesh);
  15953. }
  15954. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15955. };
  15956. _this.getScene().addMesh(_this);
  15957. _this._resyncLightSources();
  15958. return _this;
  15959. }
  15960. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15961. get: function () {
  15962. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15963. },
  15964. enumerable: true,
  15965. configurable: true
  15966. });
  15967. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15968. get: function () {
  15969. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15970. },
  15971. enumerable: true,
  15972. configurable: true
  15973. });
  15974. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15975. get: function () {
  15976. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15982. get: function () {
  15983. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15989. get: function () {
  15990. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15996. /**
  15997. * Read-only : the number of facets in the mesh
  15998. */
  15999. get: function () {
  16000. return this._facetNb;
  16001. },
  16002. enumerable: true,
  16003. configurable: true
  16004. });
  16005. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16006. /**
  16007. * The number (integer) of subdivisions per axis in the partioning space
  16008. */
  16009. get: function () {
  16010. return this._partitioningSubdivisions;
  16011. },
  16012. set: function (nb) {
  16013. this._partitioningSubdivisions = nb;
  16014. },
  16015. enumerable: true,
  16016. configurable: true
  16017. });
  16018. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16019. /**
  16020. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16021. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16022. */
  16023. get: function () {
  16024. return this._partitioningBBoxRatio;
  16025. },
  16026. set: function (ratio) {
  16027. this._partitioningBBoxRatio = ratio;
  16028. },
  16029. enumerable: true,
  16030. configurable: true
  16031. });
  16032. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16033. /**
  16034. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16035. * Works only for updatable meshes.
  16036. * Doesn't work with multi-materials.
  16037. */
  16038. get: function () {
  16039. return this._facetDepthSort;
  16040. },
  16041. set: function (sort) {
  16042. this._facetDepthSort = sort;
  16043. },
  16044. enumerable: true,
  16045. configurable: true
  16046. });
  16047. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16048. /**
  16049. * The location (Vector3) where the facet depth sort must be computed from.
  16050. * By default, the active camera position.
  16051. * Used only when facet depth sort is enabled.
  16052. */
  16053. get: function () {
  16054. return this._facetDepthSortFrom;
  16055. },
  16056. set: function (location) {
  16057. this._facetDepthSortFrom = location;
  16058. },
  16059. enumerable: true,
  16060. configurable: true
  16061. });
  16062. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16063. /**
  16064. * Read-only boolean : is the feature facetData enabled ?
  16065. */
  16066. get: function () {
  16067. return this._facetDataEnabled;
  16068. },
  16069. enumerable: true,
  16070. configurable: true
  16071. });
  16072. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16073. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16074. return false;
  16075. }
  16076. this._markSubMeshesAsMiscDirty();
  16077. return true;
  16078. };
  16079. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16080. set: function (callback) {
  16081. if (this._onCollideObserver) {
  16082. this.onCollideObservable.remove(this._onCollideObserver);
  16083. }
  16084. this._onCollideObserver = this.onCollideObservable.add(callback);
  16085. },
  16086. enumerable: true,
  16087. configurable: true
  16088. });
  16089. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16090. set: function (callback) {
  16091. if (this._onCollisionPositionChangeObserver) {
  16092. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16093. }
  16094. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16100. /**
  16101. * 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.
  16102. */
  16103. get: function () {
  16104. return this._isOccluded;
  16105. },
  16106. set: function (value) {
  16107. this._isOccluded = value;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16113. /**
  16114. * Flag to check the progress status of the query
  16115. */
  16116. get: function () {
  16117. return this._isOcclusionQueryInProgress;
  16118. },
  16119. enumerable: true,
  16120. configurable: true
  16121. });
  16122. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16123. /**
  16124. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16125. */
  16126. get: function () {
  16127. return this._visibility;
  16128. },
  16129. /**
  16130. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16131. */
  16132. set: function (value) {
  16133. if (this._visibility === value) {
  16134. return;
  16135. }
  16136. this._visibility = value;
  16137. this._markSubMeshesAsMiscDirty();
  16138. },
  16139. enumerable: true,
  16140. configurable: true
  16141. });
  16142. Object.defineProperty(AbstractMesh.prototype, "material", {
  16143. get: function () {
  16144. return this._material;
  16145. },
  16146. set: function (value) {
  16147. if (this._material === value) {
  16148. return;
  16149. }
  16150. this._material = value;
  16151. if (this.onMaterialChangedObservable.hasObservers) {
  16152. this.onMaterialChangedObservable.notifyObservers(this);
  16153. }
  16154. if (!this.subMeshes) {
  16155. return;
  16156. }
  16157. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16158. var subMesh = _a[_i];
  16159. subMesh.setEffect(null);
  16160. }
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16166. get: function () {
  16167. return this._receiveShadows;
  16168. },
  16169. set: function (value) {
  16170. if (this._receiveShadows === value) {
  16171. return;
  16172. }
  16173. this._receiveShadows = value;
  16174. this._markSubMeshesAsLightDirty();
  16175. },
  16176. enumerable: true,
  16177. configurable: true
  16178. });
  16179. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16180. get: function () {
  16181. return this._hasVertexAlpha;
  16182. },
  16183. set: function (value) {
  16184. if (this._hasVertexAlpha === value) {
  16185. return;
  16186. }
  16187. this._hasVertexAlpha = value;
  16188. this._markSubMeshesAsAttributesDirty();
  16189. this._markSubMeshesAsMiscDirty();
  16190. },
  16191. enumerable: true,
  16192. configurable: true
  16193. });
  16194. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16195. get: function () {
  16196. return this._useVertexColors;
  16197. },
  16198. set: function (value) {
  16199. if (this._useVertexColors === value) {
  16200. return;
  16201. }
  16202. this._useVertexColors = value;
  16203. this._markSubMeshesAsAttributesDirty();
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16209. get: function () {
  16210. return this._computeBonesUsingShaders;
  16211. },
  16212. set: function (value) {
  16213. if (this._computeBonesUsingShaders === value) {
  16214. return;
  16215. }
  16216. this._computeBonesUsingShaders = value;
  16217. this._markSubMeshesAsAttributesDirty();
  16218. },
  16219. enumerable: true,
  16220. configurable: true
  16221. });
  16222. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16223. get: function () {
  16224. return this._numBoneInfluencers;
  16225. },
  16226. set: function (value) {
  16227. if (this._numBoneInfluencers === value) {
  16228. return;
  16229. }
  16230. this._numBoneInfluencers = value;
  16231. this._markSubMeshesAsAttributesDirty();
  16232. },
  16233. enumerable: true,
  16234. configurable: true
  16235. });
  16236. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16237. get: function () {
  16238. return this._applyFog;
  16239. },
  16240. set: function (value) {
  16241. if (this._applyFog === value) {
  16242. return;
  16243. }
  16244. this._applyFog = value;
  16245. this._markSubMeshesAsMiscDirty();
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16251. get: function () {
  16252. return this._layerMask;
  16253. },
  16254. set: function (value) {
  16255. if (value === this._layerMask) {
  16256. return;
  16257. }
  16258. this._layerMask = value;
  16259. this._resyncLightSources();
  16260. },
  16261. enumerable: true,
  16262. configurable: true
  16263. });
  16264. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16265. get: function () {
  16266. return this._collisionMask;
  16267. },
  16268. set: function (mask) {
  16269. this._collisionMask = !isNaN(mask) ? mask : -1;
  16270. },
  16271. enumerable: true,
  16272. configurable: true
  16273. });
  16274. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16275. get: function () {
  16276. return this._collisionGroup;
  16277. },
  16278. set: function (mask) {
  16279. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16285. get: function () {
  16286. return null;
  16287. },
  16288. enumerable: true,
  16289. configurable: true
  16290. });
  16291. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16292. get: function () {
  16293. return this._skeleton;
  16294. },
  16295. set: function (value) {
  16296. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16297. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16298. }
  16299. if (value && value.needInitialSkinMatrix) {
  16300. value._registerMeshWithPoseMatrix(this);
  16301. }
  16302. this._skeleton = value;
  16303. if (!this._skeleton) {
  16304. this._bonesTransformMatrices = null;
  16305. }
  16306. this._markSubMeshesAsAttributesDirty();
  16307. },
  16308. enumerable: true,
  16309. configurable: true
  16310. });
  16311. /**
  16312. * Boolean : true if the mesh has been disposed.
  16313. */
  16314. AbstractMesh.prototype.isDisposed = function () {
  16315. return this._isDisposed;
  16316. };
  16317. /**
  16318. * Returns the string "AbstractMesh"
  16319. */
  16320. AbstractMesh.prototype.getClassName = function () {
  16321. return "AbstractMesh";
  16322. };
  16323. /**
  16324. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16325. */
  16326. AbstractMesh.prototype.toString = function (fullDetails) {
  16327. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16328. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16329. if (this._skeleton) {
  16330. ret += ", skeleton: " + this._skeleton.name;
  16331. }
  16332. if (fullDetails) {
  16333. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16334. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16335. }
  16336. return ret;
  16337. };
  16338. AbstractMesh.prototype._rebuild = function () {
  16339. if (this._occlusionQuery) {
  16340. this._occlusionQuery = null;
  16341. }
  16342. if (this._edgesRenderer) {
  16343. this._edgesRenderer._rebuild();
  16344. }
  16345. if (!this.subMeshes) {
  16346. return;
  16347. }
  16348. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16349. var subMesh = _a[_i];
  16350. subMesh._rebuild();
  16351. }
  16352. };
  16353. AbstractMesh.prototype._resyncLightSources = function () {
  16354. this._lightSources.length = 0;
  16355. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16356. var light = _a[_i];
  16357. if (!light.isEnabled()) {
  16358. continue;
  16359. }
  16360. if (light.canAffectMesh(this)) {
  16361. this._lightSources.push(light);
  16362. }
  16363. }
  16364. this._markSubMeshesAsLightDirty();
  16365. };
  16366. AbstractMesh.prototype._resyncLighSource = function (light) {
  16367. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16368. var index = this._lightSources.indexOf(light);
  16369. if (index === -1) {
  16370. if (!isIn) {
  16371. return;
  16372. }
  16373. this._lightSources.push(light);
  16374. }
  16375. else {
  16376. if (isIn) {
  16377. return;
  16378. }
  16379. this._lightSources.splice(index, 1);
  16380. }
  16381. this._markSubMeshesAsLightDirty();
  16382. };
  16383. AbstractMesh.prototype._removeLightSource = function (light) {
  16384. var index = this._lightSources.indexOf(light);
  16385. if (index === -1) {
  16386. return;
  16387. }
  16388. this._lightSources.splice(index, 1);
  16389. this._markSubMeshesAsLightDirty();
  16390. };
  16391. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16392. if (!this.subMeshes) {
  16393. return;
  16394. }
  16395. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16396. var subMesh = _a[_i];
  16397. if (subMesh._materialDefines) {
  16398. func(subMesh._materialDefines);
  16399. }
  16400. }
  16401. };
  16402. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16403. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16404. };
  16405. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16406. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16407. };
  16408. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16409. if (!this.subMeshes) {
  16410. return;
  16411. }
  16412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16413. var subMesh = _a[_i];
  16414. var material = subMesh.getMaterial();
  16415. if (material) {
  16416. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16417. }
  16418. }
  16419. };
  16420. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16421. /**
  16422. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16423. * Default : (1.0, 1.0, 1.0)
  16424. */
  16425. get: function () {
  16426. return this._scaling;
  16427. },
  16428. /**
  16429. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16430. * Default : (1.0, 1.0, 1.0)
  16431. */
  16432. set: function (newScaling) {
  16433. this._scaling = newScaling;
  16434. if (this.physicsImpostor) {
  16435. this.physicsImpostor.forceUpdate();
  16436. }
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. // Methods
  16442. /**
  16443. * Disables the mesh edger rendering mode.
  16444. * Returns the AbstractMesh.
  16445. */
  16446. AbstractMesh.prototype.disableEdgesRendering = function () {
  16447. if (this._edgesRenderer) {
  16448. this._edgesRenderer.dispose();
  16449. this._edgesRenderer = null;
  16450. }
  16451. return this;
  16452. };
  16453. /**
  16454. * Enables the edge rendering mode on the mesh.
  16455. * This mode makes the mesh edges visible.
  16456. * Returns the AbstractMesh.
  16457. */
  16458. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16459. if (epsilon === void 0) { epsilon = 0.95; }
  16460. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16461. this.disableEdgesRendering();
  16462. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16463. return this;
  16464. };
  16465. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16466. /**
  16467. * Returns true if the mesh is blocked. Used by the class Mesh.
  16468. * Returns the boolean `false` by default.
  16469. */
  16470. get: function () {
  16471. return false;
  16472. },
  16473. enumerable: true,
  16474. configurable: true
  16475. });
  16476. /**
  16477. * Returns the mesh itself by default, used by the class Mesh.
  16478. * Returned type : AbstractMesh
  16479. */
  16480. AbstractMesh.prototype.getLOD = function (camera) {
  16481. return this;
  16482. };
  16483. /**
  16484. * Returns 0 by default, used by the class Mesh.
  16485. * Returns an integer.
  16486. */
  16487. AbstractMesh.prototype.getTotalVertices = function () {
  16488. return 0;
  16489. };
  16490. /**
  16491. * Returns null by default, used by the class Mesh.
  16492. * Returned type : integer array
  16493. */
  16494. AbstractMesh.prototype.getIndices = function () {
  16495. return null;
  16496. };
  16497. /**
  16498. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16499. * Returned type : float array or Float32Array
  16500. */
  16501. AbstractMesh.prototype.getVerticesData = function (kind) {
  16502. return null;
  16503. };
  16504. /**
  16505. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16506. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16507. * The `data` are either a numeric array either a Float32Array.
  16508. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16509. * 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).
  16510. * Note that a new underlying VertexBuffer object is created each call.
  16511. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16512. *
  16513. * Possible `kind` values :
  16514. * - BABYLON.VertexBuffer.PositionKind
  16515. * - BABYLON.VertexBuffer.UVKind
  16516. * - BABYLON.VertexBuffer.UV2Kind
  16517. * - BABYLON.VertexBuffer.UV3Kind
  16518. * - BABYLON.VertexBuffer.UV4Kind
  16519. * - BABYLON.VertexBuffer.UV5Kind
  16520. * - BABYLON.VertexBuffer.UV6Kind
  16521. * - BABYLON.VertexBuffer.ColorKind
  16522. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16523. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16524. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16525. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16526. *
  16527. * Returns the Mesh.
  16528. */
  16529. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16530. return this;
  16531. };
  16532. /**
  16533. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16534. * If the mesh has no geometry, it is simply returned as it is.
  16535. * The `data` are either a numeric array either a Float32Array.
  16536. * No new underlying VertexBuffer object is created.
  16537. * 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.
  16538. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16539. *
  16540. * Possible `kind` values :
  16541. * - BABYLON.VertexBuffer.PositionKind
  16542. * - BABYLON.VertexBuffer.UVKind
  16543. * - BABYLON.VertexBuffer.UV2Kind
  16544. * - BABYLON.VertexBuffer.UV3Kind
  16545. * - BABYLON.VertexBuffer.UV4Kind
  16546. * - BABYLON.VertexBuffer.UV5Kind
  16547. * - BABYLON.VertexBuffer.UV6Kind
  16548. * - BABYLON.VertexBuffer.ColorKind
  16549. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16550. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16551. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16552. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16553. *
  16554. * Returns the Mesh.
  16555. */
  16556. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16557. return this;
  16558. };
  16559. /**
  16560. * Sets the mesh indices.
  16561. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16562. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16563. * This method creates a new index buffer each call.
  16564. * Returns the Mesh.
  16565. */
  16566. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16567. return this;
  16568. };
  16569. /** Returns false by default, used by the class Mesh.
  16570. * Returns a boolean
  16571. */
  16572. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16573. return false;
  16574. };
  16575. /**
  16576. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16577. * Returns a BoundingInfo
  16578. */
  16579. AbstractMesh.prototype.getBoundingInfo = function () {
  16580. if (this._masterMesh) {
  16581. return this._masterMesh.getBoundingInfo();
  16582. }
  16583. if (!this._boundingInfo) {
  16584. // this._boundingInfo is being created here
  16585. this._updateBoundingInfo();
  16586. }
  16587. // cannot be null.
  16588. return this._boundingInfo;
  16589. };
  16590. /**
  16591. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16592. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16593. */
  16594. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16595. if (includeDescendants === void 0) { includeDescendants = true; }
  16596. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16597. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16598. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16599. if (maxDimension === 0) {
  16600. return this;
  16601. }
  16602. var scale = 1 / maxDimension;
  16603. this.scaling.scaleInPlace(scale);
  16604. return this;
  16605. };
  16606. /**
  16607. * Sets a mesh new object BoundingInfo.
  16608. * Returns the AbstractMesh.
  16609. */
  16610. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16611. this._boundingInfo = boundingInfo;
  16612. return this;
  16613. };
  16614. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16615. get: function () {
  16616. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16617. },
  16618. enumerable: true,
  16619. configurable: true
  16620. });
  16621. AbstractMesh.prototype._preActivate = function () {
  16622. };
  16623. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16624. };
  16625. AbstractMesh.prototype._activate = function (renderId) {
  16626. this._renderId = renderId;
  16627. };
  16628. /**
  16629. * Returns the latest update of the World matrix
  16630. * Returns a Matrix.
  16631. */
  16632. AbstractMesh.prototype.getWorldMatrix = function () {
  16633. if (this._masterMesh) {
  16634. return this._masterMesh.getWorldMatrix();
  16635. }
  16636. return _super.prototype.getWorldMatrix.call(this);
  16637. };
  16638. /**
  16639. * Returns the latest update of the World matrix determinant.
  16640. */
  16641. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16642. if (this._masterMesh) {
  16643. return this._masterMesh._getWorldMatrixDeterminant();
  16644. }
  16645. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16646. };
  16647. // ================================== Point of View Movement =================================
  16648. /**
  16649. * Perform relative position change from the point of view of behind the front of the mesh.
  16650. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16651. * Supports definition of mesh facing forward or backward.
  16652. * @param {number} amountRight
  16653. * @param {number} amountUp
  16654. * @param {number} amountForward
  16655. *
  16656. * Returns the AbstractMesh.
  16657. */
  16658. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16659. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16660. return this;
  16661. };
  16662. /**
  16663. * Calculate relative position change from the point of view of behind the front of the mesh.
  16664. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16665. * Supports definition of mesh facing forward or backward.
  16666. * @param {number} amountRight
  16667. * @param {number} amountUp
  16668. * @param {number} amountForward
  16669. *
  16670. * Returns a new Vector3.
  16671. */
  16672. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16673. var rotMatrix = new BABYLON.Matrix();
  16674. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16675. rotQuaternion.toRotationMatrix(rotMatrix);
  16676. var translationDelta = BABYLON.Vector3.Zero();
  16677. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16678. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16679. return translationDelta;
  16680. };
  16681. // ================================== Point of View Rotation =================================
  16682. /**
  16683. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16684. * Supports definition of mesh facing forward or backward.
  16685. * @param {number} flipBack
  16686. * @param {number} twirlClockwise
  16687. * @param {number} tiltRight
  16688. *
  16689. * Returns the AbstractMesh.
  16690. */
  16691. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16692. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16693. return this;
  16694. };
  16695. /**
  16696. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16697. * Supports definition of mesh facing forward or backward.
  16698. * @param {number} flipBack
  16699. * @param {number} twirlClockwise
  16700. * @param {number} tiltRight
  16701. *
  16702. * Returns a new Vector3.
  16703. */
  16704. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16705. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16706. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16707. };
  16708. /**
  16709. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16710. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16711. */
  16712. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16713. if (includeDescendants === void 0) { includeDescendants = true; }
  16714. this.computeWorldMatrix(true);
  16715. var min;
  16716. var max;
  16717. var boundingInfo = this.getBoundingInfo();
  16718. if (!this.subMeshes) {
  16719. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16720. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16721. }
  16722. else {
  16723. min = boundingInfo.boundingBox.minimumWorld;
  16724. max = boundingInfo.boundingBox.maximumWorld;
  16725. }
  16726. if (includeDescendants) {
  16727. var descendants = this.getDescendants(false);
  16728. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16729. var descendant = descendants_1[_i];
  16730. var childMesh = descendant;
  16731. childMesh.computeWorldMatrix(true);
  16732. //make sure we have the needed params to get mix and max
  16733. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16734. continue;
  16735. }
  16736. var childBoundingInfo = childMesh.getBoundingInfo();
  16737. var boundingBox = childBoundingInfo.boundingBox;
  16738. var minBox = boundingBox.minimumWorld;
  16739. var maxBox = boundingBox.maximumWorld;
  16740. BABYLON.Tools.CheckExtends(minBox, min, max);
  16741. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16742. }
  16743. }
  16744. return {
  16745. min: min,
  16746. max: max
  16747. };
  16748. };
  16749. /**
  16750. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16751. * Returns the AbstractMesh.
  16752. */
  16753. AbstractMesh.prototype._updateBoundingInfo = function () {
  16754. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16755. this._boundingInfo.update(this.worldMatrixFromCache);
  16756. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16757. return this;
  16758. };
  16759. /**
  16760. * Update a mesh's children BoundingInfo objects only.
  16761. * Returns the AbstractMesh.
  16762. */
  16763. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16764. if (!this.subMeshes) {
  16765. return this;
  16766. }
  16767. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16768. var subMesh = this.subMeshes[subIndex];
  16769. if (!subMesh.IsGlobal) {
  16770. subMesh.updateBoundingInfo(matrix);
  16771. }
  16772. }
  16773. return this;
  16774. };
  16775. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16776. // Bounding info
  16777. this._updateBoundingInfo();
  16778. };
  16779. /**
  16780. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16781. * A mesh is in the frustum if its bounding box intersects the frustum.
  16782. * Boolean returned.
  16783. */
  16784. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16785. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16786. };
  16787. /**
  16788. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16789. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16790. * Boolean returned.
  16791. */
  16792. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16793. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16794. ;
  16795. };
  16796. /**
  16797. * True if the mesh intersects another mesh or a SolidParticle object.
  16798. * 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)
  16799. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16800. * Returns a boolean.
  16801. */
  16802. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16803. if (precise === void 0) { precise = false; }
  16804. if (!this._boundingInfo || !mesh._boundingInfo) {
  16805. return false;
  16806. }
  16807. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16808. return true;
  16809. }
  16810. if (includeDescendants) {
  16811. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16812. var child = _a[_i];
  16813. if (child.intersectsMesh(mesh, precise, true)) {
  16814. return true;
  16815. }
  16816. }
  16817. }
  16818. return false;
  16819. };
  16820. /**
  16821. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16822. * Returns a boolean.
  16823. */
  16824. AbstractMesh.prototype.intersectsPoint = function (point) {
  16825. if (!this._boundingInfo) {
  16826. return false;
  16827. }
  16828. return this._boundingInfo.intersectsPoint(point);
  16829. };
  16830. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16831. return this.physicsImpostor;
  16832. };
  16833. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16834. if (camera === void 0) { camera = null; }
  16835. if (!camera) {
  16836. camera = this.getScene().activeCamera;
  16837. }
  16838. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16839. };
  16840. /**
  16841. * Returns the distance from the mesh to the active camera.
  16842. * Returns a float.
  16843. */
  16844. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16845. if (camera === void 0) { camera = null; }
  16846. if (!camera) {
  16847. camera = this.getScene().activeCamera;
  16848. }
  16849. return this.absolutePosition.subtract(camera.position).length();
  16850. };
  16851. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16852. if (!this.physicsImpostor) {
  16853. return this;
  16854. }
  16855. this.physicsImpostor.applyImpulse(force, contactPoint);
  16856. return this;
  16857. };
  16858. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16859. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16860. return this;
  16861. }
  16862. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16863. mainPivot: pivot1,
  16864. connectedPivot: pivot2,
  16865. nativeParams: options
  16866. });
  16867. return this;
  16868. };
  16869. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16870. // Collisions
  16871. /**
  16872. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16873. * Default `false`.
  16874. */
  16875. get: function () {
  16876. return this._checkCollisions;
  16877. },
  16878. set: function (collisionEnabled) {
  16879. this._checkCollisions = collisionEnabled;
  16880. if (this.getScene().workerCollisions) {
  16881. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16882. }
  16883. },
  16884. enumerable: true,
  16885. configurable: true
  16886. });
  16887. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16888. /**
  16889. * Gets Collider object used to compute collisions (not physics)
  16890. */
  16891. get: function () {
  16892. return this._collider;
  16893. },
  16894. enumerable: true,
  16895. configurable: true
  16896. });
  16897. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16898. var globalPosition = this.getAbsolutePosition();
  16899. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16900. if (!this._collider) {
  16901. this._collider = new BABYLON.Collider();
  16902. }
  16903. this._collider._radius = this.ellipsoid;
  16904. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16905. return this;
  16906. };
  16907. // Submeshes octree
  16908. /**
  16909. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16910. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16911. * Returns an Octree of submeshes.
  16912. */
  16913. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16914. if (maxCapacity === void 0) { maxCapacity = 64; }
  16915. if (maxDepth === void 0) { maxDepth = 2; }
  16916. if (!this._submeshesOctree) {
  16917. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16918. }
  16919. this.computeWorldMatrix(true);
  16920. var boundingInfo = this.getBoundingInfo();
  16921. // Update octree
  16922. var bbox = boundingInfo.boundingBox;
  16923. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16924. return this._submeshesOctree;
  16925. };
  16926. // Collisions
  16927. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16928. this._generatePointsArray();
  16929. if (!this._positions) {
  16930. return this;
  16931. }
  16932. // Transformation
  16933. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16934. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16935. subMesh._lastColliderWorldVertices = [];
  16936. subMesh._trianglePlanes = [];
  16937. var start = subMesh.verticesStart;
  16938. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16939. for (var i = start; i < end; i++) {
  16940. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16941. }
  16942. }
  16943. // Collide
  16944. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16945. if (collider.collisionFound) {
  16946. collider.collidedMesh = this;
  16947. }
  16948. return this;
  16949. };
  16950. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16951. var subMeshes;
  16952. var len;
  16953. // Octrees
  16954. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16955. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16956. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16957. len = intersections.length;
  16958. subMeshes = intersections.data;
  16959. }
  16960. else {
  16961. subMeshes = this.subMeshes;
  16962. len = subMeshes.length;
  16963. }
  16964. for (var index = 0; index < len; index++) {
  16965. var subMesh = subMeshes[index];
  16966. // Bounding test
  16967. if (len > 1 && !subMesh._checkCollision(collider))
  16968. continue;
  16969. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16970. }
  16971. return this;
  16972. };
  16973. AbstractMesh.prototype._checkCollision = function (collider) {
  16974. // Bounding box test
  16975. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16976. return this;
  16977. // Transformation matrix
  16978. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16979. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16980. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16981. return this;
  16982. };
  16983. // Picking
  16984. AbstractMesh.prototype._generatePointsArray = function () {
  16985. return false;
  16986. };
  16987. /**
  16988. * Checks if the passed Ray intersects with the mesh.
  16989. * Returns an object PickingInfo.
  16990. */
  16991. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16992. var pickingInfo = new BABYLON.PickingInfo();
  16993. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16994. return pickingInfo;
  16995. }
  16996. if (!this._generatePointsArray()) {
  16997. return pickingInfo;
  16998. }
  16999. var intersectInfo = null;
  17000. // Octrees
  17001. var subMeshes;
  17002. var len;
  17003. if (this._submeshesOctree && this.useOctreeForPicking) {
  17004. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17005. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17006. len = intersections.length;
  17007. subMeshes = intersections.data;
  17008. }
  17009. else {
  17010. subMeshes = this.subMeshes;
  17011. len = subMeshes.length;
  17012. }
  17013. for (var index = 0; index < len; index++) {
  17014. var subMesh = subMeshes[index];
  17015. // Bounding test
  17016. if (len > 1 && !subMesh.canIntersects(ray))
  17017. continue;
  17018. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17019. if (currentIntersectInfo) {
  17020. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17021. intersectInfo = currentIntersectInfo;
  17022. intersectInfo.subMeshId = index;
  17023. if (fastCheck) {
  17024. break;
  17025. }
  17026. }
  17027. }
  17028. }
  17029. if (intersectInfo) {
  17030. // Get picked point
  17031. var world = this.getWorldMatrix();
  17032. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17033. var direction = ray.direction.clone();
  17034. direction = direction.scale(intersectInfo.distance);
  17035. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17036. var pickedPoint = worldOrigin.add(worldDirection);
  17037. // Return result
  17038. pickingInfo.hit = true;
  17039. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17040. pickingInfo.pickedPoint = pickedPoint;
  17041. pickingInfo.pickedMesh = this;
  17042. pickingInfo.bu = intersectInfo.bu || 0;
  17043. pickingInfo.bv = intersectInfo.bv || 0;
  17044. pickingInfo.faceId = intersectInfo.faceId;
  17045. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17046. return pickingInfo;
  17047. }
  17048. return pickingInfo;
  17049. };
  17050. /**
  17051. * Clones the mesh, used by the class Mesh.
  17052. * Just returns `null` for an AbstractMesh.
  17053. */
  17054. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17055. return null;
  17056. };
  17057. /**
  17058. * Disposes all the mesh submeshes.
  17059. * Returns the AbstractMesh.
  17060. */
  17061. AbstractMesh.prototype.releaseSubMeshes = function () {
  17062. if (this.subMeshes) {
  17063. while (this.subMeshes.length) {
  17064. this.subMeshes[0].dispose();
  17065. }
  17066. }
  17067. else {
  17068. this.subMeshes = new Array();
  17069. }
  17070. return this;
  17071. };
  17072. /**
  17073. * Disposes the AbstractMesh.
  17074. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17075. * Returns nothing.
  17076. */
  17077. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17078. var _this = this;
  17079. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17080. var index;
  17081. // Action manager
  17082. if (this.actionManager !== undefined && this.actionManager !== null) {
  17083. this.actionManager.dispose();
  17084. this.actionManager = null;
  17085. }
  17086. // Skeleton
  17087. this.skeleton = null;
  17088. // Physics
  17089. if (this.physicsImpostor) {
  17090. this.physicsImpostor.dispose();
  17091. }
  17092. // Intersections in progress
  17093. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17094. var other = this._intersectionsInProgress[index];
  17095. var pos = other._intersectionsInProgress.indexOf(this);
  17096. other._intersectionsInProgress.splice(pos, 1);
  17097. }
  17098. this._intersectionsInProgress = [];
  17099. // Lights
  17100. var lights = this.getScene().lights;
  17101. lights.forEach(function (light) {
  17102. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17103. if (meshIndex !== -1) {
  17104. light.includedOnlyMeshes.splice(meshIndex, 1);
  17105. }
  17106. meshIndex = light.excludedMeshes.indexOf(_this);
  17107. if (meshIndex !== -1) {
  17108. light.excludedMeshes.splice(meshIndex, 1);
  17109. }
  17110. // Shadow generators
  17111. var generator = light.getShadowGenerator();
  17112. if (generator) {
  17113. var shadowMap = generator.getShadowMap();
  17114. if (shadowMap && shadowMap.renderList) {
  17115. meshIndex = shadowMap.renderList.indexOf(_this);
  17116. if (meshIndex !== -1) {
  17117. shadowMap.renderList.splice(meshIndex, 1);
  17118. }
  17119. }
  17120. }
  17121. });
  17122. // Edges
  17123. if (this._edgesRenderer) {
  17124. this._edgesRenderer.dispose();
  17125. this._edgesRenderer = null;
  17126. }
  17127. // SubMeshes
  17128. if (this.getClassName() !== "InstancedMesh") {
  17129. this.releaseSubMeshes();
  17130. }
  17131. // Octree
  17132. var sceneOctree = this.getScene().selectionOctree;
  17133. if (sceneOctree !== undefined && sceneOctree !== null) {
  17134. var index = sceneOctree.dynamicContent.indexOf(this);
  17135. if (index !== -1) {
  17136. sceneOctree.dynamicContent.splice(index, 1);
  17137. }
  17138. }
  17139. // Query
  17140. var engine = this.getScene().getEngine();
  17141. if (this._occlusionQuery) {
  17142. this._isOcclusionQueryInProgress = false;
  17143. engine.deleteQuery(this._occlusionQuery);
  17144. this._occlusionQuery = null;
  17145. }
  17146. // Engine
  17147. engine.wipeCaches();
  17148. // Remove from scene
  17149. this.getScene().removeMesh(this);
  17150. if (disposeMaterialAndTextures) {
  17151. if (this.material) {
  17152. this.material.dispose(false, true);
  17153. }
  17154. }
  17155. if (!doNotRecurse) {
  17156. // Particles
  17157. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17158. if (this.getScene().particleSystems[index].emitter === this) {
  17159. this.getScene().particleSystems[index].dispose();
  17160. index--;
  17161. }
  17162. }
  17163. }
  17164. // facet data
  17165. if (this._facetDataEnabled) {
  17166. this.disableFacetData();
  17167. }
  17168. this.onAfterWorldMatrixUpdateObservable.clear();
  17169. this.onCollideObservable.clear();
  17170. this.onCollisionPositionChangeObservable.clear();
  17171. this._isDisposed = true;
  17172. _super.prototype.dispose.call(this, doNotRecurse);
  17173. };
  17174. /**
  17175. * Adds the passed mesh as a child to the current mesh.
  17176. * Returns the AbstractMesh.
  17177. */
  17178. AbstractMesh.prototype.addChild = function (mesh) {
  17179. mesh.setParent(this);
  17180. return this;
  17181. };
  17182. /**
  17183. * Removes the passed mesh from the current mesh children list.
  17184. * Returns the AbstractMesh.
  17185. */
  17186. AbstractMesh.prototype.removeChild = function (mesh) {
  17187. mesh.setParent(null);
  17188. return this;
  17189. };
  17190. // Facet data
  17191. /**
  17192. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17193. * Returns the AbstractMesh.
  17194. */
  17195. AbstractMesh.prototype._initFacetData = function () {
  17196. if (!this._facetNormals) {
  17197. this._facetNormals = new Array();
  17198. }
  17199. if (!this._facetPositions) {
  17200. this._facetPositions = new Array();
  17201. }
  17202. if (!this._facetPartitioning) {
  17203. this._facetPartitioning = new Array();
  17204. }
  17205. this._facetNb = (this.getIndices().length / 3) | 0;
  17206. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17207. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17208. for (var f = 0; f < this._facetNb; f++) {
  17209. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17210. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17211. }
  17212. this._facetDataEnabled = true;
  17213. return this;
  17214. };
  17215. /**
  17216. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17217. * This method can be called within the render loop.
  17218. * 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.
  17219. * Returns the AbstractMesh.
  17220. */
  17221. AbstractMesh.prototype.updateFacetData = function () {
  17222. if (!this._facetDataEnabled) {
  17223. this._initFacetData();
  17224. }
  17225. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17226. var indices = this.getIndices();
  17227. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17228. var bInfo = this.getBoundingInfo();
  17229. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17230. // init arrays, matrix and sort function on first call
  17231. this._facetDepthSortEnabled = true;
  17232. if (indices instanceof Uint16Array) {
  17233. this._depthSortedIndices = new Uint16Array(indices);
  17234. }
  17235. else if (indices instanceof Uint32Array) {
  17236. this._depthSortedIndices = new Uint32Array(indices);
  17237. }
  17238. else {
  17239. var needs32bits = false;
  17240. for (var i = 0; i < indices.length; i++) {
  17241. if (indices[i] > 65535) {
  17242. needs32bits = true;
  17243. break;
  17244. }
  17245. }
  17246. if (needs32bits) {
  17247. this._depthSortedIndices = new Uint32Array(indices);
  17248. }
  17249. else {
  17250. this._depthSortedIndices = new Uint16Array(indices);
  17251. }
  17252. }
  17253. this._facetDepthSortFunction = function (f1, f2) {
  17254. return (f2.sqDistance - f1.sqDistance);
  17255. };
  17256. if (!this._facetDepthSortFrom) {
  17257. var camera = this.getScene().activeCamera;
  17258. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17259. }
  17260. this._depthSortedFacets = [];
  17261. for (var f = 0; f < this._facetNb; f++) {
  17262. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17263. this._depthSortedFacets.push(depthSortedFacet);
  17264. }
  17265. this._invertedMatrix = BABYLON.Matrix.Identity();
  17266. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17267. }
  17268. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17269. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17270. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17271. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17272. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17273. this._subDiv.max = this._partitioningSubdivisions;
  17274. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17275. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17276. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17277. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17278. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17279. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17280. // set the parameters for ComputeNormals()
  17281. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17282. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17283. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17284. this._facetParameters.bInfo = bInfo;
  17285. this._facetParameters.bbSize = this._bbSize;
  17286. this._facetParameters.subDiv = this._subDiv;
  17287. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17288. this._facetParameters.depthSort = this._facetDepthSort;
  17289. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17290. this.computeWorldMatrix(true);
  17291. this._worldMatrix.invertToRef(this._invertedMatrix);
  17292. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17293. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17294. }
  17295. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17296. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17297. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17298. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17299. var l = (this._depthSortedIndices.length / 3) | 0;
  17300. for (var f = 0; f < l; f++) {
  17301. var sind = this._depthSortedFacets[f].ind;
  17302. this._depthSortedIndices[f * 3] = indices[sind];
  17303. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17304. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17305. }
  17306. this.updateIndices(this._depthSortedIndices);
  17307. }
  17308. return this;
  17309. };
  17310. /**
  17311. * Returns the facetLocalNormals array.
  17312. * The normals are expressed in the mesh local space.
  17313. */
  17314. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17315. if (!this._facetNormals) {
  17316. this.updateFacetData();
  17317. }
  17318. return this._facetNormals;
  17319. };
  17320. /**
  17321. * Returns the facetLocalPositions array.
  17322. * The facet positions are expressed in the mesh local space.
  17323. */
  17324. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17325. if (!this._facetPositions) {
  17326. this.updateFacetData();
  17327. }
  17328. return this._facetPositions;
  17329. };
  17330. /**
  17331. * Returns the facetLocalPartioning array.
  17332. */
  17333. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17334. if (!this._facetPartitioning) {
  17335. this.updateFacetData();
  17336. }
  17337. return this._facetPartitioning;
  17338. };
  17339. /**
  17340. * Returns the i-th facet position in the world system.
  17341. * This method allocates a new Vector3 per call.
  17342. */
  17343. AbstractMesh.prototype.getFacetPosition = function (i) {
  17344. var pos = BABYLON.Vector3.Zero();
  17345. this.getFacetPositionToRef(i, pos);
  17346. return pos;
  17347. };
  17348. /**
  17349. * Sets the reference Vector3 with the i-th facet position in the world system.
  17350. * Returns the AbstractMesh.
  17351. */
  17352. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17353. var localPos = (this.getFacetLocalPositions())[i];
  17354. var world = this.getWorldMatrix();
  17355. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17356. return this;
  17357. };
  17358. /**
  17359. * Returns the i-th facet normal in the world system.
  17360. * This method allocates a new Vector3 per call.
  17361. */
  17362. AbstractMesh.prototype.getFacetNormal = function (i) {
  17363. var norm = BABYLON.Vector3.Zero();
  17364. this.getFacetNormalToRef(i, norm);
  17365. return norm;
  17366. };
  17367. /**
  17368. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17369. * Returns the AbstractMesh.
  17370. */
  17371. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17372. var localNorm = (this.getFacetLocalNormals())[i];
  17373. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17374. return this;
  17375. };
  17376. /**
  17377. * 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).
  17378. */
  17379. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17380. var bInfo = this.getBoundingInfo();
  17381. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17382. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17383. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17384. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17385. return null;
  17386. }
  17387. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17388. };
  17389. /**
  17390. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17391. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17392. * 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.
  17393. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17394. * 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.
  17395. */
  17396. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17397. if (checkFace === void 0) { checkFace = false; }
  17398. if (facing === void 0) { facing = true; }
  17399. var world = this.getWorldMatrix();
  17400. var invMat = BABYLON.Tmp.Matrix[5];
  17401. world.invertToRef(invMat);
  17402. var invVect = BABYLON.Tmp.Vector3[8];
  17403. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17404. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17405. if (projected) {
  17406. // tranform the local computed projected vector to world coordinates
  17407. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17408. }
  17409. return closest;
  17410. };
  17411. /**
  17412. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17413. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17414. * 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.
  17415. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17416. * 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.
  17417. */
  17418. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17419. if (checkFace === void 0) { checkFace = false; }
  17420. if (facing === void 0) { facing = true; }
  17421. var closest = null;
  17422. var tmpx = 0.0;
  17423. var tmpy = 0.0;
  17424. var tmpz = 0.0;
  17425. var d = 0.0; // tmp dot facet normal * facet position
  17426. var t0 = 0.0;
  17427. var projx = 0.0;
  17428. var projy = 0.0;
  17429. var projz = 0.0;
  17430. // Get all the facets in the same partitioning block than (x, y, z)
  17431. var facetPositions = this.getFacetLocalPositions();
  17432. var facetNormals = this.getFacetLocalNormals();
  17433. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17434. if (!facetsInBlock) {
  17435. return null;
  17436. }
  17437. // Get the closest facet to (x, y, z)
  17438. var shortest = Number.MAX_VALUE; // init distance vars
  17439. var tmpDistance = shortest;
  17440. var fib; // current facet in the block
  17441. var norm; // current facet normal
  17442. var p0; // current facet barycenter position
  17443. // loop on all the facets in the current partitioning block
  17444. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17445. fib = facetsInBlock[idx];
  17446. norm = facetNormals[fib];
  17447. p0 = facetPositions[fib];
  17448. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17449. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17450. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17451. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17452. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17453. projx = x + norm.x * t0;
  17454. projy = y + norm.y * t0;
  17455. projz = z + norm.z * t0;
  17456. tmpx = projx - x;
  17457. tmpy = projy - y;
  17458. tmpz = projz - z;
  17459. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17460. if (tmpDistance < shortest) {
  17461. shortest = tmpDistance;
  17462. closest = fib;
  17463. if (projected) {
  17464. projected.x = projx;
  17465. projected.y = projy;
  17466. projected.z = projz;
  17467. }
  17468. }
  17469. }
  17470. }
  17471. return closest;
  17472. };
  17473. /**
  17474. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17475. */
  17476. AbstractMesh.prototype.getFacetDataParameters = function () {
  17477. return this._facetParameters;
  17478. };
  17479. /**
  17480. * Disables the feature FacetData and frees the related memory.
  17481. * Returns the AbstractMesh.
  17482. */
  17483. AbstractMesh.prototype.disableFacetData = function () {
  17484. if (this._facetDataEnabled) {
  17485. this._facetDataEnabled = false;
  17486. this._facetPositions = new Array();
  17487. this._facetNormals = new Array();
  17488. this._facetPartitioning = new Array();
  17489. this._facetParameters = null;
  17490. this._depthSortedIndices = new Uint32Array(0);
  17491. }
  17492. return this;
  17493. };
  17494. /**
  17495. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17496. * Returns the mesh.
  17497. */
  17498. AbstractMesh.prototype.updateIndices = function (indices) {
  17499. return this;
  17500. };
  17501. /**
  17502. * The mesh Geometry. Actually used by the Mesh object.
  17503. * Returns a blank geometry object.
  17504. */
  17505. /**
  17506. * Creates new normals data for the mesh.
  17507. * @param updatable.
  17508. */
  17509. AbstractMesh.prototype.createNormals = function (updatable) {
  17510. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17511. var indices = this.getIndices();
  17512. var normals;
  17513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17514. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17515. }
  17516. else {
  17517. normals = [];
  17518. }
  17519. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17520. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17521. };
  17522. /**
  17523. * Align the mesh with a normal.
  17524. * Returns the mesh.
  17525. */
  17526. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17527. if (!upDirection) {
  17528. upDirection = BABYLON.Axis.Y;
  17529. }
  17530. var axisX = BABYLON.Tmp.Vector3[0];
  17531. var axisZ = BABYLON.Tmp.Vector3[1];
  17532. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17533. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17534. if (this.rotationQuaternion) {
  17535. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17536. }
  17537. else {
  17538. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17539. }
  17540. return this;
  17541. };
  17542. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17543. var engine = this.getEngine();
  17544. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17545. this._isOccluded = false;
  17546. return;
  17547. }
  17548. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17549. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17550. if (isOcclusionQueryAvailable) {
  17551. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17552. this._isOcclusionQueryInProgress = false;
  17553. this._occlusionInternalRetryCounter = 0;
  17554. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17555. }
  17556. else {
  17557. this._occlusionInternalRetryCounter++;
  17558. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17559. this._isOcclusionQueryInProgress = false;
  17560. this._occlusionInternalRetryCounter = 0;
  17561. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17562. // if strict continue the last state of the object.
  17563. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17564. }
  17565. else {
  17566. return;
  17567. }
  17568. }
  17569. }
  17570. var scene = this.getScene();
  17571. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17572. if (!this._occlusionQuery) {
  17573. this._occlusionQuery = engine.createQuery();
  17574. }
  17575. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17576. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17577. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17578. this._isOcclusionQueryInProgress = true;
  17579. };
  17580. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17581. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17582. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17583. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17584. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17585. return AbstractMesh;
  17586. }(BABYLON.TransformNode));
  17587. BABYLON.AbstractMesh = AbstractMesh;
  17588. })(BABYLON || (BABYLON = {}));
  17589. //# sourceMappingURL=babylon.abstractMesh.js.map
  17590. var BABYLON;
  17591. (function (BABYLON) {
  17592. /**
  17593. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  17594. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  17595. * 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.
  17596. */
  17597. var Light = /** @class */ (function (_super) {
  17598. __extends(Light, _super);
  17599. /**
  17600. * Creates a Light object in the scene.
  17601. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17602. * @param name The firendly name of the light
  17603. * @param scene The scene the light belongs too
  17604. */
  17605. function Light(name, scene) {
  17606. var _this = _super.call(this, name, scene) || this;
  17607. /**
  17608. * Diffuse gives the basic color to an object.
  17609. */
  17610. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17611. /**
  17612. * Specular produces a highlight color on an object.
  17613. * Note: This is note affecting PBR materials.
  17614. */
  17615. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17616. /**
  17617. * Strength of the light.
  17618. * Note: By default it is define in the framework own unit.
  17619. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  17620. */
  17621. _this.intensity = 1.0;
  17622. /**
  17623. * Defines how far from the source the light is impacting in scene units.
  17624. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  17625. */
  17626. _this.range = Number.MAX_VALUE;
  17627. /**
  17628. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17629. * of light.
  17630. */
  17631. _this._photometricScale = 1.0;
  17632. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17633. _this._radius = 0.00001;
  17634. /**
  17635. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  17636. * exceeding the number allowed of the materials.
  17637. */
  17638. _this.renderPriority = 0;
  17639. /**
  17640. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17641. * the current shadow generator.
  17642. */
  17643. _this.shadowEnabled = true;
  17644. _this._excludeWithLayerMask = 0;
  17645. _this._includeOnlyWithLayerMask = 0;
  17646. _this._lightmapMode = 0;
  17647. /**
  17648. * @ignore Internal use only.
  17649. */
  17650. _this._excludedMeshesIds = new Array();
  17651. /**
  17652. * @ignore Internal use only.
  17653. */
  17654. _this._includedOnlyMeshesIds = new Array();
  17655. _this.getScene().addLight(_this);
  17656. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17657. _this._buildUniformLayout();
  17658. _this.includedOnlyMeshes = new Array();
  17659. _this.excludedMeshes = new Array();
  17660. _this._resyncMeshes();
  17661. return _this;
  17662. }
  17663. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17664. /**
  17665. * If every light affecting the material is in this lightmapMode,
  17666. * material.lightmapTexture adds or multiplies
  17667. * (depends on material.useLightmapAsShadowmap)
  17668. * after every other light calculations.
  17669. */
  17670. get: function () {
  17671. return Light._LIGHTMAP_DEFAULT;
  17672. },
  17673. enumerable: true,
  17674. configurable: true
  17675. });
  17676. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17677. /**
  17678. * material.lightmapTexture as only diffuse lighting from this light
  17679. * adds only specular lighting from this light
  17680. * adds dynamic shadows
  17681. */
  17682. get: function () {
  17683. return Light._LIGHTMAP_SPECULAR;
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17689. /**
  17690. * material.lightmapTexture as only lighting
  17691. * no light calculation from this light
  17692. * only adds dynamic shadows from this light
  17693. */
  17694. get: function () {
  17695. return Light._LIGHTMAP_SHADOWSONLY;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17701. /**
  17702. * Each light type uses the default quantity according to its type:
  17703. * point/spot lights use luminous intensity
  17704. * directional lights use illuminance
  17705. */
  17706. get: function () {
  17707. return Light._INTENSITYMODE_AUTOMATIC;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17713. /**
  17714. * lumen (lm)
  17715. */
  17716. get: function () {
  17717. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17723. /**
  17724. * candela (lm/sr)
  17725. */
  17726. get: function () {
  17727. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17733. /**
  17734. * lux (lm/m^2)
  17735. */
  17736. get: function () {
  17737. return Light._INTENSITYMODE_ILLUMINANCE;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17743. /**
  17744. * nit (cd/m^2)
  17745. */
  17746. get: function () {
  17747. return Light._INTENSITYMODE_LUMINANCE;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17753. /**
  17754. * Light type const id of the point light.
  17755. */
  17756. get: function () {
  17757. return Light._LIGHTTYPEID_POINTLIGHT;
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17763. /**
  17764. * Light type const id of the directional light.
  17765. */
  17766. get: function () {
  17767. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17773. /**
  17774. * Light type const id of the spot light.
  17775. */
  17776. get: function () {
  17777. return Light._LIGHTTYPEID_SPOTLIGHT;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17783. /**
  17784. * Light type const id of the hemispheric light.
  17785. */
  17786. get: function () {
  17787. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. Object.defineProperty(Light.prototype, "intensityMode", {
  17793. /**
  17794. * Gets the photometric scale used to interpret the intensity.
  17795. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17796. */
  17797. get: function () {
  17798. return this._intensityMode;
  17799. },
  17800. /**
  17801. * Sets the photometric scale used to interpret the intensity.
  17802. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17803. */
  17804. set: function (value) {
  17805. this._intensityMode = value;
  17806. this._computePhotometricScale();
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. ;
  17812. ;
  17813. Object.defineProperty(Light.prototype, "radius", {
  17814. /**
  17815. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17816. */
  17817. get: function () {
  17818. return this._radius;
  17819. },
  17820. /**
  17821. * sets the light radius used by PBR Materials to simulate soft area lights.
  17822. */
  17823. set: function (value) {
  17824. this._radius = value;
  17825. this._computePhotometricScale();
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. ;
  17831. ;
  17832. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17833. /**
  17834. * Gets the only meshes impacted by this light.
  17835. */
  17836. get: function () {
  17837. return this._includedOnlyMeshes;
  17838. },
  17839. /**
  17840. * Sets the only meshes impacted by this light.
  17841. */
  17842. set: function (value) {
  17843. this._includedOnlyMeshes = value;
  17844. this._hookArrayForIncludedOnly(value);
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17850. /**
  17851. * Gets the meshes not impacted by this light.
  17852. */
  17853. get: function () {
  17854. return this._excludedMeshes;
  17855. },
  17856. /**
  17857. * Sets the meshes not impacted by this light.
  17858. */
  17859. set: function (value) {
  17860. this._excludedMeshes = value;
  17861. this._hookArrayForExcluded(value);
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17867. /**
  17868. * Gets the layer id use to find what meshes are not impacted by the light.
  17869. * Inactive if 0
  17870. */
  17871. get: function () {
  17872. return this._excludeWithLayerMask;
  17873. },
  17874. /**
  17875. * Sets the layer id use to find what meshes are not impacted by the light.
  17876. * Inactive if 0
  17877. */
  17878. set: function (value) {
  17879. this._excludeWithLayerMask = value;
  17880. this._resyncMeshes();
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17886. /**
  17887. * Gets the layer id use to find what meshes are impacted by the light.
  17888. * Inactive if 0
  17889. */
  17890. get: function () {
  17891. return this._includeOnlyWithLayerMask;
  17892. },
  17893. /**
  17894. * Sets the layer id use to find what meshes are impacted by the light.
  17895. * Inactive if 0
  17896. */
  17897. set: function (value) {
  17898. this._includeOnlyWithLayerMask = value;
  17899. this._resyncMeshes();
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. Object.defineProperty(Light.prototype, "lightmapMode", {
  17905. /**
  17906. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17907. */
  17908. get: function () {
  17909. return this._lightmapMode;
  17910. },
  17911. /**
  17912. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17913. */
  17914. set: function (value) {
  17915. if (this._lightmapMode === value) {
  17916. return;
  17917. }
  17918. this._lightmapMode = value;
  17919. this._markMeshesAsLightDirty();
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. /**
  17925. * Returns the string "Light".
  17926. * @returns the class name
  17927. */
  17928. Light.prototype.getClassName = function () {
  17929. return "Light";
  17930. };
  17931. /**
  17932. * Converts the light information to a readable string for debug purpose.
  17933. * @param fullDetails Supports for multiple levels of logging within scene loading
  17934. * @returns the human readable light info
  17935. */
  17936. Light.prototype.toString = function (fullDetails) {
  17937. var ret = "Name: " + this.name;
  17938. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17939. if (this.animations) {
  17940. for (var i = 0; i < this.animations.length; i++) {
  17941. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17942. }
  17943. }
  17944. if (fullDetails) {
  17945. }
  17946. return ret;
  17947. };
  17948. /**
  17949. * Set the enabled state of this node.
  17950. * @param value - the new enabled state
  17951. * @see isEnabled
  17952. */
  17953. Light.prototype.setEnabled = function (value) {
  17954. _super.prototype.setEnabled.call(this, value);
  17955. this._resyncMeshes();
  17956. };
  17957. /**
  17958. * Returns the Light associated shadow generator if any.
  17959. * @return the associated shadow generator.
  17960. */
  17961. Light.prototype.getShadowGenerator = function () {
  17962. return this._shadowGenerator;
  17963. };
  17964. /**
  17965. * Returns a Vector3, the absolute light position in the World.
  17966. * @returns the world space position of the light
  17967. */
  17968. Light.prototype.getAbsolutePosition = function () {
  17969. return BABYLON.Vector3.Zero();
  17970. };
  17971. /**
  17972. * Specifies if the light will affect the passed mesh.
  17973. * @param mesh The mesh to test against the light
  17974. * @return true the mesh is affected otherwise, false.
  17975. */
  17976. Light.prototype.canAffectMesh = function (mesh) {
  17977. if (!mesh) {
  17978. return true;
  17979. }
  17980. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17981. return false;
  17982. }
  17983. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17984. return false;
  17985. }
  17986. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17987. return false;
  17988. }
  17989. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17990. return false;
  17991. }
  17992. return true;
  17993. };
  17994. /**
  17995. * Computes and Returns the light World matrix.
  17996. * @returns the world matrix
  17997. */
  17998. Light.prototype.getWorldMatrix = function () {
  17999. this._currentRenderId = this.getScene().getRenderId();
  18000. var worldMatrix = this._getWorldMatrix();
  18001. if (this.parent && this.parent.getWorldMatrix) {
  18002. if (!this._parentedWorldMatrix) {
  18003. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18004. }
  18005. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18006. this._markSyncedWithParent();
  18007. return this._parentedWorldMatrix;
  18008. }
  18009. return worldMatrix;
  18010. };
  18011. /**
  18012. * Sort function to order lights for rendering.
  18013. * @param a First Light object to compare to second.
  18014. * @param b Second Light object to compare first.
  18015. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18016. */
  18017. Light.CompareLightsPriority = function (a, b) {
  18018. //shadow-casting lights have priority over non-shadow-casting lights
  18019. //the renderPrioirty is a secondary sort criterion
  18020. if (a.shadowEnabled !== b.shadowEnabled) {
  18021. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18022. }
  18023. return b.renderPriority - a.renderPriority;
  18024. };
  18025. /**
  18026. * Disposes the light.
  18027. */
  18028. Light.prototype.dispose = function () {
  18029. if (this._shadowGenerator) {
  18030. this._shadowGenerator.dispose();
  18031. this._shadowGenerator = null;
  18032. }
  18033. // Animations
  18034. this.getScene().stopAnimation(this);
  18035. // Remove from meshes
  18036. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18037. var mesh = _a[_i];
  18038. mesh._removeLightSource(this);
  18039. }
  18040. this._uniformBuffer.dispose();
  18041. // Remove from scene
  18042. this.getScene().removeLight(this);
  18043. _super.prototype.dispose.call(this);
  18044. };
  18045. /**
  18046. * Returns the light type ID (integer).
  18047. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18048. */
  18049. Light.prototype.getTypeID = function () {
  18050. return 0;
  18051. };
  18052. /**
  18053. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18054. * @returns the scaled intensity in intensity mode unit
  18055. */
  18056. Light.prototype.getScaledIntensity = function () {
  18057. return this._photometricScale * this.intensity;
  18058. };
  18059. /**
  18060. * Returns a new Light object, named "name", from the current one.
  18061. * @param name The name of the cloned light
  18062. * @returns the new created light
  18063. */
  18064. Light.prototype.clone = function (name) {
  18065. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18066. if (!constructor) {
  18067. return null;
  18068. }
  18069. return BABYLON.SerializationHelper.Clone(constructor, this);
  18070. };
  18071. /**
  18072. * Serializes the current light into a Serialization object.
  18073. * @returns the serialized object.
  18074. */
  18075. Light.prototype.serialize = function () {
  18076. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18077. // Type
  18078. serializationObject.type = this.getTypeID();
  18079. // Parent
  18080. if (this.parent) {
  18081. serializationObject.parentId = this.parent.id;
  18082. }
  18083. // Inclusion / exclusions
  18084. if (this.excludedMeshes.length > 0) {
  18085. serializationObject.excludedMeshesIds = [];
  18086. this.excludedMeshes.forEach(function (mesh) {
  18087. serializationObject.excludedMeshesIds.push(mesh.id);
  18088. });
  18089. }
  18090. if (this.includedOnlyMeshes.length > 0) {
  18091. serializationObject.includedOnlyMeshesIds = [];
  18092. this.includedOnlyMeshes.forEach(function (mesh) {
  18093. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18094. });
  18095. }
  18096. // Animations
  18097. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18098. serializationObject.ranges = this.serializeAnimationRanges();
  18099. return serializationObject;
  18100. };
  18101. /**
  18102. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18103. * This new light is named "name" and added to the passed scene.
  18104. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18105. * @param name The friendly name of the light
  18106. * @param scene The scene the new light will belong to
  18107. * @returns the constructor function
  18108. */
  18109. Light.GetConstructorFromName = function (type, name, scene) {
  18110. switch (type) {
  18111. case 0:
  18112. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18113. case 1:
  18114. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18115. case 2:
  18116. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18117. case 3:
  18118. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18119. }
  18120. return null;
  18121. };
  18122. /**
  18123. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18124. * @param parsedLight The JSON representation of the light
  18125. * @param scene The scene to create the parsed light in
  18126. * @returns the created light after parsing
  18127. */
  18128. Light.Parse = function (parsedLight, scene) {
  18129. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18130. if (!constructor) {
  18131. return null;
  18132. }
  18133. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18134. // Inclusion / exclusions
  18135. if (parsedLight.excludedMeshesIds) {
  18136. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18137. }
  18138. if (parsedLight.includedOnlyMeshesIds) {
  18139. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18140. }
  18141. // Parent
  18142. if (parsedLight.parentId) {
  18143. light._waitingParentId = parsedLight.parentId;
  18144. }
  18145. // Animations
  18146. if (parsedLight.animations) {
  18147. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18148. var parsedAnimation = parsedLight.animations[animationIndex];
  18149. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18150. }
  18151. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18152. }
  18153. if (parsedLight.autoAnimate) {
  18154. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18155. }
  18156. return light;
  18157. };
  18158. Light.prototype._hookArrayForExcluded = function (array) {
  18159. var _this = this;
  18160. var oldPush = array.push;
  18161. array.push = function () {
  18162. var items = [];
  18163. for (var _i = 0; _i < arguments.length; _i++) {
  18164. items[_i] = arguments[_i];
  18165. }
  18166. var result = oldPush.apply(array, items);
  18167. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18168. var item = items_1[_a];
  18169. item._resyncLighSource(_this);
  18170. }
  18171. return result;
  18172. };
  18173. var oldSplice = array.splice;
  18174. array.splice = function (index, deleteCount) {
  18175. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18176. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18177. var item = deleted_1[_i];
  18178. item._resyncLighSource(_this);
  18179. }
  18180. return deleted;
  18181. };
  18182. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18183. var item = array_1[_i];
  18184. item._resyncLighSource(this);
  18185. }
  18186. };
  18187. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18188. var _this = this;
  18189. var oldPush = array.push;
  18190. array.push = function () {
  18191. var items = [];
  18192. for (var _i = 0; _i < arguments.length; _i++) {
  18193. items[_i] = arguments[_i];
  18194. }
  18195. var result = oldPush.apply(array, items);
  18196. _this._resyncMeshes();
  18197. return result;
  18198. };
  18199. var oldSplice = array.splice;
  18200. array.splice = function (index, deleteCount) {
  18201. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18202. _this._resyncMeshes();
  18203. return deleted;
  18204. };
  18205. this._resyncMeshes();
  18206. };
  18207. Light.prototype._resyncMeshes = function () {
  18208. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18209. var mesh = _a[_i];
  18210. mesh._resyncLighSource(this);
  18211. }
  18212. };
  18213. /**
  18214. * Forces the meshes to update their light related information in their rendering used effects
  18215. * @ignore Internal Use Only
  18216. */
  18217. Light.prototype._markMeshesAsLightDirty = function () {
  18218. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18219. var mesh = _a[_i];
  18220. if (mesh._lightSources.indexOf(this) !== -1) {
  18221. mesh._markSubMeshesAsLightDirty();
  18222. }
  18223. }
  18224. };
  18225. /**
  18226. * Recomputes the cached photometric scale if needed.
  18227. */
  18228. Light.prototype._computePhotometricScale = function () {
  18229. this._photometricScale = this._getPhotometricScale();
  18230. this.getScene().resetCachedMaterial();
  18231. };
  18232. /**
  18233. * Returns the Photometric Scale according to the light type and intensity mode.
  18234. */
  18235. Light.prototype._getPhotometricScale = function () {
  18236. var photometricScale = 0.0;
  18237. var lightTypeID = this.getTypeID();
  18238. //get photometric mode
  18239. var photometricMode = this.intensityMode;
  18240. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18241. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18242. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18243. }
  18244. else {
  18245. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18246. }
  18247. }
  18248. //compute photometric scale
  18249. switch (lightTypeID) {
  18250. case Light.LIGHTTYPEID_POINTLIGHT:
  18251. case Light.LIGHTTYPEID_SPOTLIGHT:
  18252. switch (photometricMode) {
  18253. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18254. photometricScale = 1.0 / (4.0 * Math.PI);
  18255. break;
  18256. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18257. photometricScale = 1.0;
  18258. break;
  18259. case Light.INTENSITYMODE_LUMINANCE:
  18260. photometricScale = this.radius * this.radius;
  18261. break;
  18262. }
  18263. break;
  18264. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18265. switch (photometricMode) {
  18266. case Light.INTENSITYMODE_ILLUMINANCE:
  18267. photometricScale = 1.0;
  18268. break;
  18269. case Light.INTENSITYMODE_LUMINANCE:
  18270. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18271. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18272. var apexAngleRadians = this.radius;
  18273. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18274. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18275. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18276. photometricScale = solidAngle;
  18277. break;
  18278. }
  18279. break;
  18280. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18281. // No fall off in hemisperic light.
  18282. photometricScale = 1.0;
  18283. break;
  18284. }
  18285. return photometricScale;
  18286. };
  18287. /**
  18288. * Reorder the light in the scene according to their defined priority.
  18289. * @ignore Internal Use Only
  18290. */
  18291. Light.prototype._reorderLightsInScene = function () {
  18292. var scene = this.getScene();
  18293. if (this._renderPriority != 0) {
  18294. scene.requireLightSorting = true;
  18295. }
  18296. this.getScene().sortLightsByPriority();
  18297. };
  18298. //lightmapMode Consts
  18299. Light._LIGHTMAP_DEFAULT = 0;
  18300. Light._LIGHTMAP_SPECULAR = 1;
  18301. Light._LIGHTMAP_SHADOWSONLY = 2;
  18302. // Intensity Mode Consts
  18303. Light._INTENSITYMODE_AUTOMATIC = 0;
  18304. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18305. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18306. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18307. Light._INTENSITYMODE_LUMINANCE = 4;
  18308. // Light types ids const.
  18309. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18310. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18311. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18312. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18313. __decorate([
  18314. BABYLON.serializeAsColor3()
  18315. ], Light.prototype, "diffuse", void 0);
  18316. __decorate([
  18317. BABYLON.serializeAsColor3()
  18318. ], Light.prototype, "specular", void 0);
  18319. __decorate([
  18320. BABYLON.serialize()
  18321. ], Light.prototype, "intensity", void 0);
  18322. __decorate([
  18323. BABYLON.serialize()
  18324. ], Light.prototype, "range", void 0);
  18325. __decorate([
  18326. BABYLON.serialize()
  18327. ], Light.prototype, "intensityMode", null);
  18328. __decorate([
  18329. BABYLON.serialize()
  18330. ], Light.prototype, "radius", null);
  18331. __decorate([
  18332. BABYLON.serialize()
  18333. ], Light.prototype, "_renderPriority", void 0);
  18334. __decorate([
  18335. BABYLON.expandToProperty("_reorderLightsInScene")
  18336. ], Light.prototype, "renderPriority", void 0);
  18337. __decorate([
  18338. BABYLON.serialize()
  18339. ], Light.prototype, "shadowEnabled", void 0);
  18340. __decorate([
  18341. BABYLON.serialize("excludeWithLayerMask")
  18342. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18343. __decorate([
  18344. BABYLON.serialize("includeOnlyWithLayerMask")
  18345. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18346. __decorate([
  18347. BABYLON.serialize("lightmapMode")
  18348. ], Light.prototype, "_lightmapMode", void 0);
  18349. return Light;
  18350. }(BABYLON.Node));
  18351. BABYLON.Light = Light;
  18352. })(BABYLON || (BABYLON = {}));
  18353. //# sourceMappingURL=babylon.light.js.map
  18354. var BABYLON;
  18355. (function (BABYLON) {
  18356. var Camera = /** @class */ (function (_super) {
  18357. __extends(Camera, _super);
  18358. function Camera(name, position, scene) {
  18359. var _this = _super.call(this, name, scene) || this;
  18360. /**
  18361. * The vector the camera should consider as up.
  18362. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18363. */
  18364. _this.upVector = BABYLON.Vector3.Up();
  18365. _this.orthoLeft = null;
  18366. _this.orthoRight = null;
  18367. _this.orthoBottom = null;
  18368. _this.orthoTop = null;
  18369. /**
  18370. * FOV is set in Radians. (default is 0.8)
  18371. */
  18372. _this.fov = 0.8;
  18373. _this.minZ = 1;
  18374. _this.maxZ = 10000.0;
  18375. _this.inertia = 0.9;
  18376. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18377. _this.isIntermediate = false;
  18378. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18379. /**
  18380. * Restricts the camera to viewing objects with the same layerMask.
  18381. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18382. */
  18383. _this.layerMask = 0x0FFFFFFF;
  18384. /**
  18385. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18386. */
  18387. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18388. // Camera rig members
  18389. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18390. _this._rigCameras = new Array();
  18391. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18392. _this._skipRendering = false;
  18393. _this.customRenderTargets = new Array();
  18394. // Observables
  18395. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18396. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18397. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18398. _this.onRestoreStateObservable = new BABYLON.Observable();
  18399. // Cache
  18400. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18401. _this._projectionMatrix = new BABYLON.Matrix();
  18402. _this._doNotComputeProjectionMatrix = false;
  18403. _this._postProcesses = new Array();
  18404. _this._transformMatrix = BABYLON.Matrix.Zero();
  18405. _this._activeMeshes = new BABYLON.SmartArray(256);
  18406. _this._globalPosition = BABYLON.Vector3.Zero();
  18407. _this._refreshFrustumPlanes = true;
  18408. _this.getScene().addCamera(_this);
  18409. if (!_this.getScene().activeCamera) {
  18410. _this.getScene().activeCamera = _this;
  18411. }
  18412. _this.position = position;
  18413. return _this;
  18414. }
  18415. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18416. get: function () {
  18417. return Camera._PERSPECTIVE_CAMERA;
  18418. },
  18419. enumerable: true,
  18420. configurable: true
  18421. });
  18422. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18423. get: function () {
  18424. return Camera._ORTHOGRAPHIC_CAMERA;
  18425. },
  18426. enumerable: true,
  18427. configurable: true
  18428. });
  18429. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18430. /**
  18431. * This is the default FOV mode for perspective cameras.
  18432. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18433. *
  18434. */
  18435. get: function () {
  18436. return Camera._FOVMODE_VERTICAL_FIXED;
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18442. /**
  18443. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18444. *
  18445. */
  18446. get: function () {
  18447. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18453. get: function () {
  18454. return Camera._RIG_MODE_NONE;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18460. get: function () {
  18461. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18467. get: function () {
  18468. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18474. get: function () {
  18475. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18481. get: function () {
  18482. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18488. get: function () {
  18489. return Camera._RIG_MODE_VR;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18495. get: function () {
  18496. return Camera._RIG_MODE_WEBVR;
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. /**
  18502. * Store current camera state (fov, position, etc..)
  18503. */
  18504. Camera.prototype.storeState = function () {
  18505. this._stateStored = true;
  18506. this._storedFov = this.fov;
  18507. return this;
  18508. };
  18509. /**
  18510. * Restores the camera state values if it has been stored. You must call storeState() first
  18511. */
  18512. Camera.prototype._restoreStateValues = function () {
  18513. if (!this._stateStored) {
  18514. return false;
  18515. }
  18516. this.fov = this._storedFov;
  18517. return true;
  18518. };
  18519. /**
  18520. * Restored camera state. You must call storeState() first
  18521. */
  18522. Camera.prototype.restoreState = function () {
  18523. if (this._restoreStateValues()) {
  18524. this.onRestoreStateObservable.notifyObservers(this);
  18525. return true;
  18526. }
  18527. return false;
  18528. };
  18529. Camera.prototype.getClassName = function () {
  18530. return "Camera";
  18531. };
  18532. /**
  18533. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18534. */
  18535. Camera.prototype.toString = function (fullDetails) {
  18536. var ret = "Name: " + this.name;
  18537. ret += ", type: " + this.getClassName();
  18538. if (this.animations) {
  18539. for (var i = 0; i < this.animations.length; i++) {
  18540. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18541. }
  18542. }
  18543. if (fullDetails) {
  18544. }
  18545. return ret;
  18546. };
  18547. Object.defineProperty(Camera.prototype, "globalPosition", {
  18548. get: function () {
  18549. return this._globalPosition;
  18550. },
  18551. enumerable: true,
  18552. configurable: true
  18553. });
  18554. Camera.prototype.getActiveMeshes = function () {
  18555. return this._activeMeshes;
  18556. };
  18557. Camera.prototype.isActiveMesh = function (mesh) {
  18558. return (this._activeMeshes.indexOf(mesh) !== -1);
  18559. };
  18560. //Cache
  18561. Camera.prototype._initCache = function () {
  18562. _super.prototype._initCache.call(this);
  18563. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18564. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18565. this._cache.mode = undefined;
  18566. this._cache.minZ = undefined;
  18567. this._cache.maxZ = undefined;
  18568. this._cache.fov = undefined;
  18569. this._cache.fovMode = undefined;
  18570. this._cache.aspectRatio = undefined;
  18571. this._cache.orthoLeft = undefined;
  18572. this._cache.orthoRight = undefined;
  18573. this._cache.orthoBottom = undefined;
  18574. this._cache.orthoTop = undefined;
  18575. this._cache.renderWidth = undefined;
  18576. this._cache.renderHeight = undefined;
  18577. };
  18578. Camera.prototype._updateCache = function (ignoreParentClass) {
  18579. if (!ignoreParentClass) {
  18580. _super.prototype._updateCache.call(this);
  18581. }
  18582. this._cache.position.copyFrom(this.position);
  18583. this._cache.upVector.copyFrom(this.upVector);
  18584. };
  18585. // Synchronized
  18586. Camera.prototype._isSynchronized = function () {
  18587. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18588. };
  18589. Camera.prototype._isSynchronizedViewMatrix = function () {
  18590. if (!_super.prototype._isSynchronized.call(this))
  18591. return false;
  18592. return this._cache.position.equals(this.position)
  18593. && this._cache.upVector.equals(this.upVector)
  18594. && this.isSynchronizedWithParent();
  18595. };
  18596. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18597. var check = this._cache.mode === this.mode
  18598. && this._cache.minZ === this.minZ
  18599. && this._cache.maxZ === this.maxZ;
  18600. if (!check) {
  18601. return false;
  18602. }
  18603. var engine = this.getEngine();
  18604. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18605. check = this._cache.fov === this.fov
  18606. && this._cache.fovMode === this.fovMode
  18607. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18608. }
  18609. else {
  18610. check = this._cache.orthoLeft === this.orthoLeft
  18611. && this._cache.orthoRight === this.orthoRight
  18612. && this._cache.orthoBottom === this.orthoBottom
  18613. && this._cache.orthoTop === this.orthoTop
  18614. && this._cache.renderWidth === engine.getRenderWidth()
  18615. && this._cache.renderHeight === engine.getRenderHeight();
  18616. }
  18617. return check;
  18618. };
  18619. // Controls
  18620. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18621. };
  18622. Camera.prototype.detachControl = function (element) {
  18623. };
  18624. Camera.prototype.update = function () {
  18625. this._checkInputs();
  18626. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18627. this._updateRigCameras();
  18628. }
  18629. };
  18630. Camera.prototype._checkInputs = function () {
  18631. this.onAfterCheckInputsObservable.notifyObservers(this);
  18632. };
  18633. Object.defineProperty(Camera.prototype, "rigCameras", {
  18634. get: function () {
  18635. return this._rigCameras;
  18636. },
  18637. enumerable: true,
  18638. configurable: true
  18639. });
  18640. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18641. get: function () {
  18642. return this._rigPostProcess;
  18643. },
  18644. enumerable: true,
  18645. configurable: true
  18646. });
  18647. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18648. // invalidate framebuffer
  18649. if (this._postProcesses.length > 0) {
  18650. this._postProcesses[0].markTextureDirty();
  18651. }
  18652. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18653. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18654. var cam = this._rigCameras[i];
  18655. var rigPostProcess = cam._rigPostProcess;
  18656. // for VR rig, there does not have to be a post process
  18657. if (rigPostProcess) {
  18658. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18659. if (isPass) {
  18660. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18661. cam.isIntermediate = this._postProcesses.length === 0;
  18662. }
  18663. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18664. rigPostProcess.markTextureDirty();
  18665. }
  18666. else {
  18667. cam._postProcesses = this._postProcesses.slice(0);
  18668. }
  18669. }
  18670. };
  18671. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18672. if (insertAt === void 0) { insertAt = null; }
  18673. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18674. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18675. return 0;
  18676. }
  18677. if (insertAt == null || insertAt < 0) {
  18678. this._postProcesses.push(postProcess);
  18679. }
  18680. else {
  18681. this._postProcesses.splice(insertAt, 0, postProcess);
  18682. }
  18683. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18684. return this._postProcesses.indexOf(postProcess);
  18685. };
  18686. Camera.prototype.detachPostProcess = function (postProcess) {
  18687. var idx = this._postProcesses.indexOf(postProcess);
  18688. if (idx !== -1) {
  18689. this._postProcesses.splice(idx, 1);
  18690. }
  18691. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18692. };
  18693. Camera.prototype.getWorldMatrix = function () {
  18694. if (!this._worldMatrix) {
  18695. this._worldMatrix = BABYLON.Matrix.Identity();
  18696. }
  18697. var viewMatrix = this.getViewMatrix();
  18698. viewMatrix.invertToRef(this._worldMatrix);
  18699. return this._worldMatrix;
  18700. };
  18701. Camera.prototype._getViewMatrix = function () {
  18702. return BABYLON.Matrix.Identity();
  18703. };
  18704. Camera.prototype.getViewMatrix = function (force) {
  18705. if (!force && this._isSynchronizedViewMatrix()) {
  18706. return this._computedViewMatrix;
  18707. }
  18708. this.updateCache();
  18709. this._computedViewMatrix = this._getViewMatrix();
  18710. this._currentRenderId = this.getScene().getRenderId();
  18711. this._refreshFrustumPlanes = true;
  18712. if (!this.parent || !this.parent.getWorldMatrix) {
  18713. this._globalPosition.copyFrom(this.position);
  18714. }
  18715. else {
  18716. if (!this._worldMatrix) {
  18717. this._worldMatrix = BABYLON.Matrix.Identity();
  18718. }
  18719. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18720. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18721. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18722. this._computedViewMatrix.invert();
  18723. this._markSyncedWithParent();
  18724. }
  18725. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18726. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18727. }
  18728. this.onViewMatrixChangedObservable.notifyObservers(this);
  18729. return this._computedViewMatrix;
  18730. };
  18731. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18732. this._doNotComputeProjectionMatrix = true;
  18733. if (projection !== undefined) {
  18734. this._projectionMatrix = projection;
  18735. }
  18736. };
  18737. ;
  18738. Camera.prototype.unfreezeProjectionMatrix = function () {
  18739. this._doNotComputeProjectionMatrix = false;
  18740. };
  18741. ;
  18742. Camera.prototype.getProjectionMatrix = function (force) {
  18743. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18744. return this._projectionMatrix;
  18745. }
  18746. // Cache
  18747. this._cache.mode = this.mode;
  18748. this._cache.minZ = this.minZ;
  18749. this._cache.maxZ = this.maxZ;
  18750. // Matrix
  18751. this._refreshFrustumPlanes = true;
  18752. var engine = this.getEngine();
  18753. var scene = this.getScene();
  18754. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18755. this._cache.fov = this.fov;
  18756. this._cache.fovMode = this.fovMode;
  18757. this._cache.aspectRatio = engine.getAspectRatio(this);
  18758. if (this.minZ <= 0) {
  18759. this.minZ = 0.1;
  18760. }
  18761. if (scene.useRightHandedSystem) {
  18762. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18763. }
  18764. else {
  18765. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18766. }
  18767. }
  18768. else {
  18769. var halfWidth = engine.getRenderWidth() / 2.0;
  18770. var halfHeight = engine.getRenderHeight() / 2.0;
  18771. if (scene.useRightHandedSystem) {
  18772. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18773. }
  18774. else {
  18775. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18776. }
  18777. this._cache.orthoLeft = this.orthoLeft;
  18778. this._cache.orthoRight = this.orthoRight;
  18779. this._cache.orthoBottom = this.orthoBottom;
  18780. this._cache.orthoTop = this.orthoTop;
  18781. this._cache.renderWidth = engine.getRenderWidth();
  18782. this._cache.renderHeight = engine.getRenderHeight();
  18783. }
  18784. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18785. return this._projectionMatrix;
  18786. };
  18787. Camera.prototype.getTranformationMatrix = function () {
  18788. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18789. return this._transformMatrix;
  18790. };
  18791. Camera.prototype.updateFrustumPlanes = function () {
  18792. if (!this._refreshFrustumPlanes) {
  18793. return;
  18794. }
  18795. this.getTranformationMatrix();
  18796. if (!this._frustumPlanes) {
  18797. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18798. }
  18799. else {
  18800. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18801. }
  18802. this._refreshFrustumPlanes = false;
  18803. };
  18804. Camera.prototype.isInFrustum = function (target) {
  18805. this.updateFrustumPlanes();
  18806. return target.isInFrustum(this._frustumPlanes);
  18807. };
  18808. Camera.prototype.isCompletelyInFrustum = function (target) {
  18809. this.updateFrustumPlanes();
  18810. return target.isCompletelyInFrustum(this._frustumPlanes);
  18811. };
  18812. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18813. if (length === void 0) { length = 100; }
  18814. if (!transform) {
  18815. transform = this.getWorldMatrix();
  18816. }
  18817. if (!origin) {
  18818. origin = this.position;
  18819. }
  18820. var forward = new BABYLON.Vector3(0, 0, 1);
  18821. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18822. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18823. return new BABYLON.Ray(origin, direction, length);
  18824. };
  18825. Camera.prototype.dispose = function () {
  18826. // Observables
  18827. this.onViewMatrixChangedObservable.clear();
  18828. this.onProjectionMatrixChangedObservable.clear();
  18829. this.onAfterCheckInputsObservable.clear();
  18830. this.onRestoreStateObservable.clear();
  18831. // Inputs
  18832. if (this.inputs) {
  18833. this.inputs.clear();
  18834. }
  18835. // Animations
  18836. this.getScene().stopAnimation(this);
  18837. // Remove from scene
  18838. this.getScene().removeCamera(this);
  18839. while (this._rigCameras.length > 0) {
  18840. var camera = this._rigCameras.pop();
  18841. if (camera) {
  18842. camera.dispose();
  18843. }
  18844. }
  18845. // Postprocesses
  18846. if (this._rigPostProcess) {
  18847. this._rigPostProcess.dispose(this);
  18848. this._rigPostProcess = null;
  18849. this._postProcesses = [];
  18850. }
  18851. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18852. this._rigPostProcess = null;
  18853. this._postProcesses = [];
  18854. }
  18855. else {
  18856. var i = this._postProcesses.length;
  18857. while (--i >= 0) {
  18858. this._postProcesses[i].dispose(this);
  18859. }
  18860. }
  18861. // Render targets
  18862. var i = this.customRenderTargets.length;
  18863. while (--i >= 0) {
  18864. this.customRenderTargets[i].dispose();
  18865. }
  18866. this.customRenderTargets = [];
  18867. // Active Meshes
  18868. this._activeMeshes.dispose();
  18869. _super.prototype.dispose.call(this);
  18870. };
  18871. Object.defineProperty(Camera.prototype, "leftCamera", {
  18872. // ---- Camera rigs section ----
  18873. get: function () {
  18874. if (this._rigCameras.length < 1) {
  18875. return null;
  18876. }
  18877. return this._rigCameras[0];
  18878. },
  18879. enumerable: true,
  18880. configurable: true
  18881. });
  18882. Object.defineProperty(Camera.prototype, "rightCamera", {
  18883. get: function () {
  18884. if (this._rigCameras.length < 2) {
  18885. return null;
  18886. }
  18887. return this._rigCameras[1];
  18888. },
  18889. enumerable: true,
  18890. configurable: true
  18891. });
  18892. Camera.prototype.getLeftTarget = function () {
  18893. if (this._rigCameras.length < 1) {
  18894. return null;
  18895. }
  18896. return this._rigCameras[0].getTarget();
  18897. };
  18898. Camera.prototype.getRightTarget = function () {
  18899. if (this._rigCameras.length < 2) {
  18900. return null;
  18901. }
  18902. return this._rigCameras[1].getTarget();
  18903. };
  18904. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18905. if (this.cameraRigMode === mode) {
  18906. return;
  18907. }
  18908. while (this._rigCameras.length > 0) {
  18909. var camera = this._rigCameras.pop();
  18910. if (camera) {
  18911. camera.dispose();
  18912. }
  18913. }
  18914. this.cameraRigMode = mode;
  18915. this._cameraRigParams = {};
  18916. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18917. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18918. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18919. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18920. // create the rig cameras, unless none
  18921. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18922. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18923. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18924. if (leftCamera && rightCamera) {
  18925. this._rigCameras.push(leftCamera);
  18926. this._rigCameras.push(rightCamera);
  18927. }
  18928. }
  18929. switch (this.cameraRigMode) {
  18930. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18931. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18932. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18933. break;
  18934. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18935. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18936. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18937. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18938. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18939. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18940. break;
  18941. case Camera.RIG_MODE_VR:
  18942. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18943. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18944. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18945. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18946. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18947. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18948. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18949. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18950. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18951. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18952. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18953. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18954. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18955. if (metrics.compensateDistortion) {
  18956. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18957. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18958. }
  18959. break;
  18960. case Camera.RIG_MODE_WEBVR:
  18961. if (rigParams.vrDisplay) {
  18962. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18963. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18964. //Left eye
  18965. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18966. this._rigCameras[0].setCameraRigParameter("left", true);
  18967. //leaving this for future reference
  18968. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18969. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18970. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18971. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18972. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18973. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18974. this._rigCameras[0].parent = this;
  18975. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18976. //Right eye
  18977. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18978. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18979. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18980. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18981. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18982. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18983. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18984. this._rigCameras[1].parent = this;
  18985. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18986. if (Camera.UseAlternateWebVRRendering) {
  18987. this._rigCameras[1]._skipRendering = true;
  18988. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18989. }
  18990. }
  18991. break;
  18992. }
  18993. this._cascadePostProcessesToRigCams();
  18994. this.update();
  18995. };
  18996. Camera.prototype._getVRProjectionMatrix = function () {
  18997. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18998. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18999. return this._projectionMatrix;
  19000. };
  19001. Camera.prototype._updateCameraRotationMatrix = function () {
  19002. //Here for WebVR
  19003. };
  19004. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19005. //Here for WebVR
  19006. };
  19007. /**
  19008. * This function MUST be overwritten by the different WebVR cameras available.
  19009. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19010. */
  19011. Camera.prototype._getWebVRProjectionMatrix = function () {
  19012. return BABYLON.Matrix.Identity();
  19013. };
  19014. /**
  19015. * This function MUST be overwritten by the different WebVR cameras available.
  19016. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19017. */
  19018. Camera.prototype._getWebVRViewMatrix = function () {
  19019. return BABYLON.Matrix.Identity();
  19020. };
  19021. Camera.prototype.setCameraRigParameter = function (name, value) {
  19022. if (!this._cameraRigParams) {
  19023. this._cameraRigParams = {};
  19024. }
  19025. this._cameraRigParams[name] = value;
  19026. //provisionnally:
  19027. if (name === "interaxialDistance") {
  19028. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19029. }
  19030. };
  19031. /**
  19032. * needs to be overridden by children so sub has required properties to be copied
  19033. */
  19034. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19035. return null;
  19036. };
  19037. /**
  19038. * May need to be overridden by children
  19039. */
  19040. Camera.prototype._updateRigCameras = function () {
  19041. for (var i = 0; i < this._rigCameras.length; i++) {
  19042. this._rigCameras[i].minZ = this.minZ;
  19043. this._rigCameras[i].maxZ = this.maxZ;
  19044. this._rigCameras[i].fov = this.fov;
  19045. }
  19046. // only update viewport when ANAGLYPH
  19047. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19048. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19049. }
  19050. };
  19051. Camera.prototype._setupInputs = function () {
  19052. };
  19053. Camera.prototype.serialize = function () {
  19054. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19055. // Type
  19056. serializationObject.type = this.getClassName();
  19057. // Parent
  19058. if (this.parent) {
  19059. serializationObject.parentId = this.parent.id;
  19060. }
  19061. if (this.inputs) {
  19062. this.inputs.serialize(serializationObject);
  19063. }
  19064. // Animations
  19065. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19066. serializationObject.ranges = this.serializeAnimationRanges();
  19067. return serializationObject;
  19068. };
  19069. Camera.prototype.clone = function (name) {
  19070. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19071. };
  19072. Camera.prototype.getDirection = function (localAxis) {
  19073. var result = BABYLON.Vector3.Zero();
  19074. this.getDirectionToRef(localAxis, result);
  19075. return result;
  19076. };
  19077. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19078. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19079. };
  19080. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19081. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19082. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19083. switch (type) {
  19084. case "ArcRotateCamera":
  19085. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19086. case "DeviceOrientationCamera":
  19087. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19088. case "FollowCamera":
  19089. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19090. case "ArcFollowCamera":
  19091. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19092. case "GamepadCamera":
  19093. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19094. case "TouchCamera":
  19095. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19096. case "VirtualJoysticksCamera":
  19097. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19098. case "WebVRFreeCamera":
  19099. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19100. case "WebVRGamepadCamera":
  19101. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19102. case "VRDeviceOrientationFreeCamera":
  19103. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19104. case "VRDeviceOrientationGamepadCamera":
  19105. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19106. case "AnaglyphArcRotateCamera":
  19107. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19108. case "AnaglyphFreeCamera":
  19109. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19110. case "AnaglyphGamepadCamera":
  19111. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19112. case "AnaglyphUniversalCamera":
  19113. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19114. case "StereoscopicArcRotateCamera":
  19115. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19116. case "StereoscopicFreeCamera":
  19117. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19118. case "StereoscopicGamepadCamera":
  19119. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19120. case "StereoscopicUniversalCamera":
  19121. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19122. case "FreeCamera":// Forcing Universal here
  19123. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19124. default:// Universal Camera is the default value
  19125. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19126. }
  19127. };
  19128. Camera.prototype.computeWorldMatrix = function () {
  19129. return this.getWorldMatrix();
  19130. };
  19131. Camera.Parse = function (parsedCamera, scene) {
  19132. var type = parsedCamera.type;
  19133. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19134. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19135. // Parent
  19136. if (parsedCamera.parentId) {
  19137. camera._waitingParentId = parsedCamera.parentId;
  19138. }
  19139. //If camera has an input manager, let it parse inputs settings
  19140. if (camera.inputs) {
  19141. camera.inputs.parse(parsedCamera);
  19142. camera._setupInputs();
  19143. }
  19144. if (camera.setPosition) {
  19145. camera.position.copyFromFloats(0, 0, 0);
  19146. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19147. }
  19148. // Target
  19149. if (parsedCamera.target) {
  19150. if (camera.setTarget) {
  19151. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19152. }
  19153. }
  19154. // Apply 3d rig, when found
  19155. if (parsedCamera.cameraRigMode) {
  19156. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19157. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19158. }
  19159. // Animations
  19160. if (parsedCamera.animations) {
  19161. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19162. var parsedAnimation = parsedCamera.animations[animationIndex];
  19163. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19164. }
  19165. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19166. }
  19167. if (parsedCamera.autoAnimate) {
  19168. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19169. }
  19170. return camera;
  19171. };
  19172. // Statics
  19173. Camera._PERSPECTIVE_CAMERA = 0;
  19174. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19175. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19176. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19177. Camera._RIG_MODE_NONE = 0;
  19178. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19179. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19180. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19181. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19182. Camera._RIG_MODE_VR = 20;
  19183. Camera._RIG_MODE_WEBVR = 21;
  19184. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19185. Camera.UseAlternateWebVRRendering = false;
  19186. __decorate([
  19187. BABYLON.serializeAsVector3()
  19188. ], Camera.prototype, "position", void 0);
  19189. __decorate([
  19190. BABYLON.serializeAsVector3()
  19191. ], Camera.prototype, "upVector", void 0);
  19192. __decorate([
  19193. BABYLON.serialize()
  19194. ], Camera.prototype, "orthoLeft", void 0);
  19195. __decorate([
  19196. BABYLON.serialize()
  19197. ], Camera.prototype, "orthoRight", void 0);
  19198. __decorate([
  19199. BABYLON.serialize()
  19200. ], Camera.prototype, "orthoBottom", void 0);
  19201. __decorate([
  19202. BABYLON.serialize()
  19203. ], Camera.prototype, "orthoTop", void 0);
  19204. __decorate([
  19205. BABYLON.serialize()
  19206. ], Camera.prototype, "fov", void 0);
  19207. __decorate([
  19208. BABYLON.serialize()
  19209. ], Camera.prototype, "minZ", void 0);
  19210. __decorate([
  19211. BABYLON.serialize()
  19212. ], Camera.prototype, "maxZ", void 0);
  19213. __decorate([
  19214. BABYLON.serialize()
  19215. ], Camera.prototype, "inertia", void 0);
  19216. __decorate([
  19217. BABYLON.serialize()
  19218. ], Camera.prototype, "mode", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], Camera.prototype, "layerMask", void 0);
  19222. __decorate([
  19223. BABYLON.serialize()
  19224. ], Camera.prototype, "fovMode", void 0);
  19225. __decorate([
  19226. BABYLON.serialize()
  19227. ], Camera.prototype, "cameraRigMode", void 0);
  19228. __decorate([
  19229. BABYLON.serialize()
  19230. ], Camera.prototype, "interaxialDistance", void 0);
  19231. __decorate([
  19232. BABYLON.serialize()
  19233. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19234. return Camera;
  19235. }(BABYLON.Node));
  19236. BABYLON.Camera = Camera;
  19237. })(BABYLON || (BABYLON = {}));
  19238. //# sourceMappingURL=babylon.camera.js.map
  19239. var BABYLON;
  19240. (function (BABYLON) {
  19241. var RenderingManager = /** @class */ (function () {
  19242. function RenderingManager(scene) {
  19243. this._renderingGroups = new Array();
  19244. this._autoClearDepthStencil = {};
  19245. this._customOpaqueSortCompareFn = {};
  19246. this._customAlphaTestSortCompareFn = {};
  19247. this._customTransparentSortCompareFn = {};
  19248. this._renderinGroupInfo = null;
  19249. this._scene = scene;
  19250. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19251. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19252. }
  19253. }
  19254. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19255. if (depth === void 0) { depth = true; }
  19256. if (stencil === void 0) { stencil = true; }
  19257. if (this._depthStencilBufferAlreadyCleaned) {
  19258. return;
  19259. }
  19260. this._scene.getEngine().clear(null, false, depth, stencil);
  19261. this._depthStencilBufferAlreadyCleaned = true;
  19262. };
  19263. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19264. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19265. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19266. var info = null;
  19267. if (observable) {
  19268. if (!this._renderinGroupInfo) {
  19269. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19270. }
  19271. info = this._renderinGroupInfo;
  19272. info.scene = this._scene;
  19273. info.camera = this._scene.activeCamera;
  19274. }
  19275. // Dispatch sprites
  19276. if (renderSprites) {
  19277. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19278. var manager = this._scene.spriteManagers[index];
  19279. this.dispatchSprites(manager);
  19280. }
  19281. }
  19282. // Render
  19283. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19284. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19285. var renderingGroup = this._renderingGroups[index];
  19286. if (!renderingGroup && !observable)
  19287. continue;
  19288. var renderingGroupMask = 0;
  19289. // Fire PRECLEAR stage
  19290. if (observable && info) {
  19291. renderingGroupMask = Math.pow(2, index);
  19292. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19293. info.renderingGroupId = index;
  19294. observable.notifyObservers(info, renderingGroupMask);
  19295. }
  19296. // Clear depth/stencil if needed
  19297. if (RenderingManager.AUTOCLEAR) {
  19298. var autoClear = this._autoClearDepthStencil[index];
  19299. if (autoClear && autoClear.autoClear) {
  19300. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19301. }
  19302. }
  19303. if (observable && info) {
  19304. // Fire PREOPAQUE stage
  19305. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19306. observable.notifyObservers(info, renderingGroupMask);
  19307. // Fire PRETRANSPARENT stage
  19308. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19309. observable.notifyObservers(info, renderingGroupMask);
  19310. }
  19311. if (renderingGroup)
  19312. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19313. // Fire POSTTRANSPARENT stage
  19314. if (observable && info) {
  19315. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19316. observable.notifyObservers(info, renderingGroupMask);
  19317. }
  19318. }
  19319. };
  19320. RenderingManager.prototype.reset = function () {
  19321. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19322. var renderingGroup = this._renderingGroups[index];
  19323. if (renderingGroup) {
  19324. renderingGroup.prepare();
  19325. }
  19326. }
  19327. };
  19328. RenderingManager.prototype.dispose = function () {
  19329. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19330. var renderingGroup = this._renderingGroups[index];
  19331. if (renderingGroup) {
  19332. renderingGroup.dispose();
  19333. }
  19334. }
  19335. this._renderingGroups.length = 0;
  19336. };
  19337. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19338. if (this._renderingGroups[renderingGroupId] === undefined) {
  19339. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19340. }
  19341. };
  19342. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19343. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19344. this._prepareRenderingGroup(renderingGroupId);
  19345. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19346. };
  19347. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19348. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19349. this._prepareRenderingGroup(renderingGroupId);
  19350. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19351. };
  19352. /**
  19353. * @param subMesh The submesh to dispatch
  19354. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19355. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19356. */
  19357. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19358. if (mesh === undefined) {
  19359. mesh = subMesh.getMesh();
  19360. }
  19361. var renderingGroupId = mesh.renderingGroupId || 0;
  19362. this._prepareRenderingGroup(renderingGroupId);
  19363. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19364. };
  19365. /**
  19366. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19367. * This allowed control for front to back rendering or reversly depending of the special needs.
  19368. *
  19369. * @param renderingGroupId The rendering group id corresponding to its index
  19370. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19371. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19372. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19373. */
  19374. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19375. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19376. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19377. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19378. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19379. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19380. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19381. if (this._renderingGroups[renderingGroupId]) {
  19382. var group = this._renderingGroups[renderingGroupId];
  19383. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19384. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19385. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19386. }
  19387. };
  19388. /**
  19389. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19390. *
  19391. * @param renderingGroupId The rendering group id corresponding to its index
  19392. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19393. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19394. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19395. */
  19396. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19397. if (depth === void 0) { depth = true; }
  19398. if (stencil === void 0) { stencil = true; }
  19399. this._autoClearDepthStencil[renderingGroupId] = {
  19400. autoClear: autoClearDepthStencil,
  19401. depth: depth,
  19402. stencil: stencil
  19403. };
  19404. };
  19405. /**
  19406. * The max id used for rendering groups (not included)
  19407. */
  19408. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19409. /**
  19410. * The min id used for rendering groups (included)
  19411. */
  19412. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19413. /**
  19414. * Used to globally prevent autoclearing scenes.
  19415. */
  19416. RenderingManager.AUTOCLEAR = true;
  19417. return RenderingManager;
  19418. }());
  19419. BABYLON.RenderingManager = RenderingManager;
  19420. })(BABYLON || (BABYLON = {}));
  19421. //# sourceMappingURL=babylon.renderingManager.js.map
  19422. var BABYLON;
  19423. (function (BABYLON) {
  19424. var RenderingGroup = /** @class */ (function () {
  19425. /**
  19426. * Creates a new rendering group.
  19427. * @param index The rendering group index
  19428. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19429. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19430. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19431. */
  19432. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19433. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19434. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19435. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19436. this.index = index;
  19437. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19438. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19439. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19440. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19441. this._particleSystems = new BABYLON.SmartArray(256);
  19442. this._spriteManagers = new BABYLON.SmartArray(256);
  19443. this._edgesRenderers = new BABYLON.SmartArray(16);
  19444. this._scene = scene;
  19445. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19446. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19447. this.transparentSortCompareFn = transparentSortCompareFn;
  19448. }
  19449. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19450. /**
  19451. * Set the opaque sort comparison function.
  19452. * If null the sub meshes will be render in the order they were created
  19453. */
  19454. set: function (value) {
  19455. this._opaqueSortCompareFn = value;
  19456. if (value) {
  19457. this._renderOpaque = this.renderOpaqueSorted;
  19458. }
  19459. else {
  19460. this._renderOpaque = RenderingGroup.renderUnsorted;
  19461. }
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19467. /**
  19468. * Set the alpha test sort comparison function.
  19469. * If null the sub meshes will be render in the order they were created
  19470. */
  19471. set: function (value) {
  19472. this._alphaTestSortCompareFn = value;
  19473. if (value) {
  19474. this._renderAlphaTest = this.renderAlphaTestSorted;
  19475. }
  19476. else {
  19477. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19478. }
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19484. /**
  19485. * Set the transparent sort comparison function.
  19486. * If null the sub meshes will be render in the order they were created
  19487. */
  19488. set: function (value) {
  19489. if (value) {
  19490. this._transparentSortCompareFn = value;
  19491. }
  19492. else {
  19493. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19494. }
  19495. this._renderTransparent = this.renderTransparentSorted;
  19496. },
  19497. enumerable: true,
  19498. configurable: true
  19499. });
  19500. /**
  19501. * Render all the sub meshes contained in the group.
  19502. * @param customRenderFunction Used to override the default render behaviour of the group.
  19503. * @returns true if rendered some submeshes.
  19504. */
  19505. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19506. if (customRenderFunction) {
  19507. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19508. return;
  19509. }
  19510. var engine = this._scene.getEngine();
  19511. // Depth only
  19512. if (this._depthOnlySubMeshes.length !== 0) {
  19513. engine.setColorWrite(false);
  19514. this._renderAlphaTest(this._depthOnlySubMeshes);
  19515. engine.setColorWrite(true);
  19516. }
  19517. // Opaque
  19518. if (this._opaqueSubMeshes.length !== 0) {
  19519. this._renderOpaque(this._opaqueSubMeshes);
  19520. }
  19521. // Alpha test
  19522. if (this._alphaTestSubMeshes.length !== 0) {
  19523. this._renderAlphaTest(this._alphaTestSubMeshes);
  19524. }
  19525. var stencilState = engine.getStencilBuffer();
  19526. engine.setStencilBuffer(false);
  19527. // Sprites
  19528. if (renderSprites) {
  19529. this._renderSprites();
  19530. }
  19531. // Particles
  19532. if (renderParticles) {
  19533. this._renderParticles(activeMeshes);
  19534. }
  19535. if (this.onBeforeTransparentRendering) {
  19536. this.onBeforeTransparentRendering();
  19537. }
  19538. // Transparent
  19539. if (this._transparentSubMeshes.length !== 0) {
  19540. this._renderTransparent(this._transparentSubMeshes);
  19541. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19542. }
  19543. // Set back stencil to false in case it changes before the edge renderer.
  19544. engine.setStencilBuffer(false);
  19545. // Edges
  19546. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19547. this._edgesRenderers.data[edgesRendererIndex].render();
  19548. }
  19549. // Restore Stencil state.
  19550. engine.setStencilBuffer(stencilState);
  19551. };
  19552. /**
  19553. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19554. * @param subMeshes The submeshes to render
  19555. */
  19556. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19557. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19558. };
  19559. /**
  19560. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19561. * @param subMeshes The submeshes to render
  19562. */
  19563. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19564. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19565. };
  19566. /**
  19567. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19568. * @param subMeshes The submeshes to render
  19569. */
  19570. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19571. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19572. };
  19573. /**
  19574. * Renders the submeshes in a specified order.
  19575. * @param subMeshes The submeshes to sort before render
  19576. * @param sortCompareFn The comparison function use to sort
  19577. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19578. * @param transparent Specifies to activate blending if true
  19579. */
  19580. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19581. var subIndex = 0;
  19582. var subMesh;
  19583. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19584. for (; subIndex < subMeshes.length; subIndex++) {
  19585. subMesh = subMeshes.data[subIndex];
  19586. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19587. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19588. }
  19589. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19590. if (sortCompareFn) {
  19591. sortedArray.sort(sortCompareFn);
  19592. }
  19593. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19594. subMesh = sortedArray[subIndex];
  19595. if (transparent) {
  19596. var material = subMesh.getMaterial();
  19597. if (material && material.needDepthPrePass) {
  19598. var engine = material.getScene().getEngine();
  19599. engine.setColorWrite(false);
  19600. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19601. subMesh.render(false);
  19602. engine.setColorWrite(true);
  19603. }
  19604. }
  19605. subMesh.render(transparent);
  19606. }
  19607. };
  19608. /**
  19609. * Renders the submeshes in the order they were dispatched (no sort applied).
  19610. * @param subMeshes The submeshes to render
  19611. */
  19612. RenderingGroup.renderUnsorted = function (subMeshes) {
  19613. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19614. var submesh = subMeshes.data[subIndex];
  19615. submesh.render(false);
  19616. }
  19617. };
  19618. /**
  19619. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19620. * are rendered back to front if in the same alpha index.
  19621. *
  19622. * @param a The first submesh
  19623. * @param b The second submesh
  19624. * @returns The result of the comparison
  19625. */
  19626. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19627. // Alpha index first
  19628. if (a._alphaIndex > b._alphaIndex) {
  19629. return 1;
  19630. }
  19631. if (a._alphaIndex < b._alphaIndex) {
  19632. return -1;
  19633. }
  19634. // Then distance to camera
  19635. return RenderingGroup.backToFrontSortCompare(a, b);
  19636. };
  19637. /**
  19638. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19639. * are rendered back to front.
  19640. *
  19641. * @param a The first submesh
  19642. * @param b The second submesh
  19643. * @returns The result of the comparison
  19644. */
  19645. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19646. // Then distance to camera
  19647. if (a._distanceToCamera < b._distanceToCamera) {
  19648. return 1;
  19649. }
  19650. if (a._distanceToCamera > b._distanceToCamera) {
  19651. return -1;
  19652. }
  19653. return 0;
  19654. };
  19655. /**
  19656. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19657. * are rendered front to back (prevent overdraw).
  19658. *
  19659. * @param a The first submesh
  19660. * @param b The second submesh
  19661. * @returns The result of the comparison
  19662. */
  19663. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19664. // Then distance to camera
  19665. if (a._distanceToCamera < b._distanceToCamera) {
  19666. return -1;
  19667. }
  19668. if (a._distanceToCamera > b._distanceToCamera) {
  19669. return 1;
  19670. }
  19671. return 0;
  19672. };
  19673. /**
  19674. * Resets the different lists of submeshes to prepare a new frame.
  19675. */
  19676. RenderingGroup.prototype.prepare = function () {
  19677. this._opaqueSubMeshes.reset();
  19678. this._transparentSubMeshes.reset();
  19679. this._alphaTestSubMeshes.reset();
  19680. this._depthOnlySubMeshes.reset();
  19681. this._particleSystems.reset();
  19682. this._spriteManagers.reset();
  19683. this._edgesRenderers.reset();
  19684. };
  19685. RenderingGroup.prototype.dispose = function () {
  19686. this._opaqueSubMeshes.dispose();
  19687. this._transparentSubMeshes.dispose();
  19688. this._alphaTestSubMeshes.dispose();
  19689. this._depthOnlySubMeshes.dispose();
  19690. this._particleSystems.dispose();
  19691. this._spriteManagers.dispose();
  19692. this._edgesRenderers.dispose();
  19693. };
  19694. /**
  19695. * Inserts the submesh in its correct queue depending on its material.
  19696. * @param subMesh The submesh to dispatch
  19697. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19698. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19699. */
  19700. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19701. // Get mesh and materials if not provided
  19702. if (mesh === undefined) {
  19703. mesh = subMesh.getMesh();
  19704. }
  19705. if (material === undefined) {
  19706. material = subMesh.getMaterial();
  19707. }
  19708. if (material === null || material === undefined) {
  19709. return;
  19710. }
  19711. if (material.needAlphaBlendingForMesh(mesh)) {
  19712. this._transparentSubMeshes.push(subMesh);
  19713. }
  19714. else if (material.needAlphaTesting()) {
  19715. if (material.needDepthPrePass) {
  19716. this._depthOnlySubMeshes.push(subMesh);
  19717. }
  19718. this._alphaTestSubMeshes.push(subMesh);
  19719. }
  19720. else {
  19721. if (material.needDepthPrePass) {
  19722. this._depthOnlySubMeshes.push(subMesh);
  19723. }
  19724. this._opaqueSubMeshes.push(subMesh); // Opaque
  19725. }
  19726. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19727. this._edgesRenderers.push(mesh._edgesRenderer);
  19728. }
  19729. };
  19730. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19731. this._spriteManagers.push(spriteManager);
  19732. };
  19733. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19734. this._particleSystems.push(particleSystem);
  19735. };
  19736. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19737. if (this._particleSystems.length === 0) {
  19738. return;
  19739. }
  19740. // Particles
  19741. var activeCamera = this._scene.activeCamera;
  19742. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19743. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19744. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19745. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19746. continue;
  19747. }
  19748. var emitter = particleSystem.emitter;
  19749. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19750. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19751. }
  19752. }
  19753. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19754. };
  19755. RenderingGroup.prototype._renderSprites = function () {
  19756. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19757. return;
  19758. }
  19759. // Sprites
  19760. var activeCamera = this._scene.activeCamera;
  19761. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19762. for (var id = 0; id < this._spriteManagers.length; id++) {
  19763. var spriteManager = this._spriteManagers.data[id];
  19764. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19765. spriteManager.render();
  19766. }
  19767. }
  19768. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19769. };
  19770. return RenderingGroup;
  19771. }());
  19772. BABYLON.RenderingGroup = RenderingGroup;
  19773. })(BABYLON || (BABYLON = {}));
  19774. //# sourceMappingURL=babylon.renderingGroup.js.map
  19775. var BABYLON;
  19776. (function (BABYLON) {
  19777. var ClickInfo = /** @class */ (function () {
  19778. function ClickInfo() {
  19779. this._singleClick = false;
  19780. this._doubleClick = false;
  19781. this._hasSwiped = false;
  19782. this._ignore = false;
  19783. }
  19784. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19785. get: function () {
  19786. return this._singleClick;
  19787. },
  19788. set: function (b) {
  19789. this._singleClick = b;
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19795. get: function () {
  19796. return this._doubleClick;
  19797. },
  19798. set: function (b) {
  19799. this._doubleClick = b;
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19805. get: function () {
  19806. return this._hasSwiped;
  19807. },
  19808. set: function (b) {
  19809. this._hasSwiped = b;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19815. get: function () {
  19816. return this._ignore;
  19817. },
  19818. set: function (b) {
  19819. this._ignore = b;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. return ClickInfo;
  19825. }());
  19826. /**
  19827. * This class is used by the onRenderingGroupObservable
  19828. */
  19829. var RenderingGroupInfo = /** @class */ (function () {
  19830. function RenderingGroupInfo() {
  19831. }
  19832. /**
  19833. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19834. * This stage will be fired no matter what
  19835. */
  19836. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19837. /**
  19838. * Called before opaque object are rendered.
  19839. * This stage will be fired only if there's 3D Opaque content to render
  19840. */
  19841. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19842. /**
  19843. * Called after the opaque objects are rendered and before the transparent ones
  19844. * This stage will be fired only if there's 3D transparent content to render
  19845. */
  19846. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19847. /**
  19848. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19849. * This stage will be fired no matter what
  19850. */
  19851. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19852. return RenderingGroupInfo;
  19853. }());
  19854. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19855. /**
  19856. * Represents a scene to be rendered by the engine.
  19857. * @see http://doc.babylonjs.com/page.php?p=21911
  19858. */
  19859. var Scene = /** @class */ (function () {
  19860. /**
  19861. * @constructor
  19862. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19863. */
  19864. function Scene(engine) {
  19865. // Members
  19866. this.autoClear = true;
  19867. this.autoClearDepthAndStencil = true;
  19868. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19869. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19870. this.forceWireframe = false;
  19871. this._forcePointsCloud = false;
  19872. this.forceShowBoundingBoxes = false;
  19873. this.animationsEnabled = true;
  19874. this.useConstantAnimationDeltaTime = false;
  19875. this.constantlyUpdateMeshUnderPointer = false;
  19876. this.hoverCursor = "pointer";
  19877. this.defaultCursor = "";
  19878. /**
  19879. * This is used to call preventDefault() on pointer down
  19880. * in order to block unwanted artifacts like system double clicks
  19881. */
  19882. this.preventDefaultOnPointerDown = true;
  19883. // Metadata
  19884. this.metadata = null;
  19885. /**
  19886. * An event triggered when the scene is disposed.
  19887. * @type {BABYLON.Observable}
  19888. */
  19889. this.onDisposeObservable = new BABYLON.Observable();
  19890. /**
  19891. * An event triggered before rendering the scene (right after animations and physics)
  19892. * @type {BABYLON.Observable}
  19893. */
  19894. this.onBeforeRenderObservable = new BABYLON.Observable();
  19895. /**
  19896. * An event triggered after rendering the scene
  19897. * @type {BABYLON.Observable}
  19898. */
  19899. this.onAfterRenderObservable = new BABYLON.Observable();
  19900. /**
  19901. * An event triggered before animating the scene
  19902. * @type {BABYLON.Observable}
  19903. */
  19904. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19905. /**
  19906. * An event triggered after animations processing
  19907. * @type {BABYLON.Observable}
  19908. */
  19909. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19910. /**
  19911. * An event triggered before draw calls are ready to be sent
  19912. * @type {BABYLON.Observable}
  19913. */
  19914. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19915. /**
  19916. * An event triggered after draw calls have been sent
  19917. * @type {BABYLON.Observable}
  19918. */
  19919. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19920. /**
  19921. * An event triggered when physic simulation is about to be run
  19922. * @type {BABYLON.Observable}
  19923. */
  19924. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19925. /**
  19926. * An event triggered when physic simulation has been done
  19927. * @type {BABYLON.Observable}
  19928. */
  19929. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19930. /**
  19931. * An event triggered when the scene is ready
  19932. * @type {BABYLON.Observable}
  19933. */
  19934. this.onReadyObservable = new BABYLON.Observable();
  19935. /**
  19936. * An event triggered before rendering a camera
  19937. * @type {BABYLON.Observable}
  19938. */
  19939. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19940. /**
  19941. * An event triggered after rendering a camera
  19942. * @type {BABYLON.Observable}
  19943. */
  19944. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19945. /**
  19946. * An event triggered when active meshes evaluation is about to start
  19947. * @type {BABYLON.Observable}
  19948. */
  19949. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19950. /**
  19951. * An event triggered when active meshes evaluation is done
  19952. * @type {BABYLON.Observable}
  19953. */
  19954. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19955. /**
  19956. * An event triggered when particles rendering is about to start
  19957. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19958. * @type {BABYLON.Observable}
  19959. */
  19960. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19961. /**
  19962. * An event triggered when particles rendering is done
  19963. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19964. * @type {BABYLON.Observable}
  19965. */
  19966. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19967. /**
  19968. * An event triggered when sprites rendering is about to start
  19969. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19970. * @type {BABYLON.Observable}
  19971. */
  19972. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19973. /**
  19974. * An event triggered when sprites rendering is done
  19975. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19976. * @type {BABYLON.Observable}
  19977. */
  19978. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19979. /**
  19980. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19981. * @type {BABYLON.Observable}
  19982. */
  19983. this.onDataLoadedObservable = new BABYLON.Observable();
  19984. /**
  19985. * An event triggered when a camera is created
  19986. * @type {BABYLON.Observable}
  19987. */
  19988. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19989. /**
  19990. * An event triggered when a camera is removed
  19991. * @type {BABYLON.Observable}
  19992. */
  19993. this.onCameraRemovedObservable = new BABYLON.Observable();
  19994. /**
  19995. * An event triggered when a light is created
  19996. * @type {BABYLON.Observable}
  19997. */
  19998. this.onNewLightAddedObservable = new BABYLON.Observable();
  19999. /**
  20000. * An event triggered when a light is removed
  20001. * @type {BABYLON.Observable}
  20002. */
  20003. this.onLightRemovedObservable = new BABYLON.Observable();
  20004. /**
  20005. * An event triggered when a geometry is created
  20006. * @type {BABYLON.Observable}
  20007. */
  20008. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20009. /**
  20010. * An event triggered when a geometry is removed
  20011. * @type {BABYLON.Observable}
  20012. */
  20013. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20014. /**
  20015. * An event triggered when a transform node is created
  20016. * @type {BABYLON.Observable}
  20017. */
  20018. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20019. /**
  20020. * An event triggered when a transform node is removed
  20021. * @type {BABYLON.Observable}
  20022. */
  20023. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20024. /**
  20025. * An event triggered when a mesh is created
  20026. * @type {BABYLON.Observable}
  20027. */
  20028. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20029. /**
  20030. * An event triggered when a mesh is removed
  20031. * @type {BABYLON.Observable}
  20032. */
  20033. this.onMeshRemovedObservable = new BABYLON.Observable();
  20034. /**
  20035. * An event triggered when render targets are about to be rendered
  20036. * Can happen multiple times per frame.
  20037. * @type {BABYLON.Observable}
  20038. */
  20039. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20040. /**
  20041. * An event triggered when render targets were rendered.
  20042. * Can happen multiple times per frame.
  20043. * @type {BABYLON.Observable}
  20044. */
  20045. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20046. /**
  20047. * An event triggered before calculating deterministic simulation step
  20048. * @type {BABYLON.Observable}
  20049. */
  20050. this.onBeforeStepObservable = new BABYLON.Observable();
  20051. /**
  20052. * An event triggered after calculating deterministic simulation step
  20053. * @type {BABYLON.Observable}
  20054. */
  20055. this.onAfterStepObservable = new BABYLON.Observable();
  20056. /**
  20057. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20058. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20059. * 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)
  20060. */
  20061. this.onRenderingGroupObservable = new BABYLON.Observable();
  20062. // Animations
  20063. this.animations = [];
  20064. /**
  20065. * 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).
  20066. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20067. */
  20068. this.onPrePointerObservable = new BABYLON.Observable();
  20069. /**
  20070. * Observable event triggered each time an input event is received from the rendering canvas
  20071. */
  20072. this.onPointerObservable = new BABYLON.Observable();
  20073. this._meshPickProceed = false;
  20074. this._currentPickResult = null;
  20075. this._previousPickResult = null;
  20076. this._totalPointersPressed = 0;
  20077. this._doubleClickOccured = false;
  20078. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20079. this.cameraToUseForPointers = null;
  20080. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20081. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20082. this._startingPointerTime = 0;
  20083. this._previousStartingPointerTime = 0;
  20084. // Deterministic lockstep
  20085. this._timeAccumulator = 0;
  20086. this._currentStepId = 0;
  20087. this._currentInternalStep = 0;
  20088. // Keyboard
  20089. /**
  20090. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20091. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20092. */
  20093. this.onPreKeyboardObservable = new BABYLON.Observable();
  20094. /**
  20095. * Observable event triggered each time an keyboard event is received from the hosting window
  20096. */
  20097. this.onKeyboardObservable = new BABYLON.Observable();
  20098. // Coordinate system
  20099. /**
  20100. * use right-handed coordinate system on this scene.
  20101. * @type {boolean}
  20102. */
  20103. this._useRightHandedSystem = false;
  20104. // Fog
  20105. this._fogEnabled = true;
  20106. this._fogMode = Scene.FOGMODE_NONE;
  20107. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20108. this.fogDensity = 0.1;
  20109. this.fogStart = 0;
  20110. this.fogEnd = 1000.0;
  20111. // Lights
  20112. /**
  20113. * is shadow enabled on this scene.
  20114. * @type {boolean}
  20115. */
  20116. this._shadowsEnabled = true;
  20117. /**
  20118. * is light enabled on this scene.
  20119. * @type {boolean}
  20120. */
  20121. this._lightsEnabled = true;
  20122. /**
  20123. * All of the lights added to this scene.
  20124. * @see BABYLON.Light
  20125. * @type {BABYLON.Light[]}
  20126. */
  20127. this.lights = new Array();
  20128. // Cameras
  20129. /** All of the cameras added to this scene. */
  20130. this.cameras = new Array();
  20131. /** All of the active cameras added to this scene. */
  20132. this.activeCameras = new Array();
  20133. // Meshes
  20134. /**
  20135. * All of the tranform nodes added to this scene.
  20136. * @see BABYLON.TransformNode
  20137. * @type {BABYLON.TransformNode[]}
  20138. */
  20139. this.transformNodes = new Array();
  20140. /**
  20141. * All of the (abstract) meshes added to this scene.
  20142. * @see BABYLON.AbstractMesh
  20143. * @type {BABYLON.AbstractMesh[]}
  20144. */
  20145. this.meshes = new Array();
  20146. /**
  20147. * All of the animation groups added to this scene.
  20148. * @see BABYLON.AnimationGroup
  20149. * @type {BABYLON.AnimationGroup[]}
  20150. */
  20151. this.animationGroups = new Array();
  20152. // Geometries
  20153. this._geometries = new Array();
  20154. this.materials = new Array();
  20155. this.multiMaterials = new Array();
  20156. // Textures
  20157. this._texturesEnabled = true;
  20158. this.textures = new Array();
  20159. // Particles
  20160. this.particlesEnabled = true;
  20161. this.particleSystems = new Array();
  20162. // Sprites
  20163. this.spritesEnabled = true;
  20164. this.spriteManagers = new Array();
  20165. // Layers
  20166. this.layers = new Array();
  20167. this.highlightLayers = new Array();
  20168. // Skeletons
  20169. this._skeletonsEnabled = true;
  20170. this.skeletons = new Array();
  20171. // Morph targets
  20172. this.morphTargetManagers = new Array();
  20173. // Lens flares
  20174. this.lensFlaresEnabled = true;
  20175. this.lensFlareSystems = new Array();
  20176. // Collisions
  20177. this.collisionsEnabled = true;
  20178. /** Defines the gravity applied to this scene */
  20179. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20180. // Postprocesses
  20181. this.postProcesses = new Array();
  20182. this.postProcessesEnabled = true;
  20183. // Customs render targets
  20184. this.renderTargetsEnabled = true;
  20185. this.dumpNextRenderTargets = false;
  20186. this.customRenderTargets = new Array();
  20187. // Imported meshes
  20188. this.importedMeshesFiles = new Array();
  20189. // Probes
  20190. this.probesEnabled = true;
  20191. this.reflectionProbes = new Array();
  20192. this._actionManagers = new Array();
  20193. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20194. // Procedural textures
  20195. this.proceduralTexturesEnabled = true;
  20196. this._proceduralTextures = new Array();
  20197. this.soundTracks = new Array();
  20198. this._audioEnabled = true;
  20199. this._headphone = false;
  20200. // Performance counters
  20201. this._totalVertices = new BABYLON.PerfCounter();
  20202. this._activeIndices = new BABYLON.PerfCounter();
  20203. this._activeParticles = new BABYLON.PerfCounter();
  20204. this._activeBones = new BABYLON.PerfCounter();
  20205. this._animationTime = 0;
  20206. this.animationTimeScale = 1;
  20207. this._renderId = 0;
  20208. this._executeWhenReadyTimeoutId = -1;
  20209. this._intermediateRendering = false;
  20210. this._viewUpdateFlag = -1;
  20211. this._projectionUpdateFlag = -1;
  20212. this._alternateViewUpdateFlag = -1;
  20213. this._alternateProjectionUpdateFlag = -1;
  20214. this._toBeDisposed = new BABYLON.SmartArray(256);
  20215. this._activeRequests = new Array();
  20216. this._pendingData = new Array();
  20217. this._isDisposed = false;
  20218. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20219. this._activeMeshes = new BABYLON.SmartArray(256);
  20220. this._processedMaterials = new BABYLON.SmartArray(256);
  20221. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20222. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20223. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20224. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20225. this._activeAnimatables = new Array();
  20226. this._transformMatrix = BABYLON.Matrix.Zero();
  20227. this._useAlternateCameraConfiguration = false;
  20228. this._alternateRendering = false;
  20229. this.requireLightSorting = false;
  20230. this._activeMeshesFrozen = false;
  20231. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20232. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20233. this._engine.scenes.push(this);
  20234. this._uid = null;
  20235. this._renderingManager = new BABYLON.RenderingManager(this);
  20236. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20237. if (BABYLON.OutlineRenderer) {
  20238. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20239. }
  20240. if (BABYLON.Tools.IsWindowObjectExist()) {
  20241. this.attachControl();
  20242. }
  20243. //simplification queue
  20244. if (BABYLON.SimplificationQueue) {
  20245. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20246. }
  20247. //collision coordinator initialization. For now legacy per default.
  20248. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20249. // Uniform Buffer
  20250. this._createUbo();
  20251. // Default Image processing definition.
  20252. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20253. }
  20254. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20255. /** The fog is deactivated */
  20256. get: function () {
  20257. return Scene._FOGMODE_NONE;
  20258. },
  20259. enumerable: true,
  20260. configurable: true
  20261. });
  20262. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20263. /** The fog density is following an exponential function */
  20264. get: function () {
  20265. return Scene._FOGMODE_EXP;
  20266. },
  20267. enumerable: true,
  20268. configurable: true
  20269. });
  20270. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20271. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20272. get: function () {
  20273. return Scene._FOGMODE_EXP2;
  20274. },
  20275. enumerable: true,
  20276. configurable: true
  20277. });
  20278. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20279. /** The fog density is following a linear function. */
  20280. get: function () {
  20281. return Scene._FOGMODE_LINEAR;
  20282. },
  20283. enumerable: true,
  20284. configurable: true
  20285. });
  20286. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20287. /**
  20288. * Texture used in all pbr material as the reflection texture.
  20289. * As in the majority of the scene they are the same (exception for multi room and so on),
  20290. * this is easier to reference from here than from all the materials.
  20291. */
  20292. get: function () {
  20293. return this._environmentTexture;
  20294. },
  20295. /**
  20296. * Texture used in all pbr material as the reflection texture.
  20297. * As in the majority of the scene they are the same (exception for multi room and so on),
  20298. * this is easier to set here than in all the materials.
  20299. */
  20300. set: function (value) {
  20301. if (this._environmentTexture === value) {
  20302. return;
  20303. }
  20304. this._environmentTexture = value;
  20305. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20306. },
  20307. enumerable: true,
  20308. configurable: true
  20309. });
  20310. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20311. /**
  20312. * Default image processing configuration used either in the rendering
  20313. * Forward main pass or through the imageProcessingPostProcess if present.
  20314. * As in the majority of the scene they are the same (exception for multi camera),
  20315. * this is easier to reference from here than from all the materials and post process.
  20316. *
  20317. * No setter as we it is a shared configuration, you can set the values instead.
  20318. */
  20319. get: function () {
  20320. return this._imageProcessingConfiguration;
  20321. },
  20322. enumerable: true,
  20323. configurable: true
  20324. });
  20325. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20326. get: function () {
  20327. return this._forcePointsCloud;
  20328. },
  20329. set: function (value) {
  20330. if (this._forcePointsCloud === value) {
  20331. return;
  20332. }
  20333. this._forcePointsCloud = value;
  20334. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20335. },
  20336. enumerable: true,
  20337. configurable: true
  20338. });
  20339. Object.defineProperty(Scene.prototype, "onDispose", {
  20340. /** A function to be executed when this scene is disposed. */
  20341. set: function (callback) {
  20342. if (this._onDisposeObserver) {
  20343. this.onDisposeObservable.remove(this._onDisposeObserver);
  20344. }
  20345. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20346. },
  20347. enumerable: true,
  20348. configurable: true
  20349. });
  20350. Object.defineProperty(Scene.prototype, "beforeRender", {
  20351. /** A function to be executed before rendering this scene */
  20352. set: function (callback) {
  20353. if (this._onBeforeRenderObserver) {
  20354. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20355. }
  20356. if (callback) {
  20357. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20358. }
  20359. },
  20360. enumerable: true,
  20361. configurable: true
  20362. });
  20363. Object.defineProperty(Scene.prototype, "afterRender", {
  20364. /** A function to be executed after rendering this scene */
  20365. set: function (callback) {
  20366. if (this._onAfterRenderObserver) {
  20367. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20368. }
  20369. if (callback) {
  20370. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20371. }
  20372. },
  20373. enumerable: true,
  20374. configurable: true
  20375. });
  20376. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20377. set: function (callback) {
  20378. if (this._onBeforeCameraRenderObserver) {
  20379. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20380. }
  20381. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20382. },
  20383. enumerable: true,
  20384. configurable: true
  20385. });
  20386. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20387. set: function (callback) {
  20388. if (this._onAfterCameraRenderObserver) {
  20389. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20390. }
  20391. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20392. },
  20393. enumerable: true,
  20394. configurable: true
  20395. });
  20396. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20397. get: function () {
  20398. if (!this._gamepadManager) {
  20399. this._gamepadManager = new BABYLON.GamepadManager(this);
  20400. }
  20401. return this._gamepadManager;
  20402. },
  20403. enumerable: true,
  20404. configurable: true
  20405. });
  20406. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20407. get: function () {
  20408. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20409. },
  20410. enumerable: true,
  20411. configurable: true
  20412. });
  20413. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20414. get: function () {
  20415. return this._useRightHandedSystem;
  20416. },
  20417. set: function (value) {
  20418. if (this._useRightHandedSystem === value) {
  20419. return;
  20420. }
  20421. this._useRightHandedSystem = value;
  20422. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20423. },
  20424. enumerable: true,
  20425. configurable: true
  20426. });
  20427. Scene.prototype.setStepId = function (newStepId) {
  20428. this._currentStepId = newStepId;
  20429. };
  20430. ;
  20431. Scene.prototype.getStepId = function () {
  20432. return this._currentStepId;
  20433. };
  20434. ;
  20435. Scene.prototype.getInternalStep = function () {
  20436. return this._currentInternalStep;
  20437. };
  20438. ;
  20439. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20440. get: function () {
  20441. return this._fogEnabled;
  20442. },
  20443. /**
  20444. * is fog enabled on this scene.
  20445. */
  20446. set: function (value) {
  20447. if (this._fogEnabled === value) {
  20448. return;
  20449. }
  20450. this._fogEnabled = value;
  20451. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20452. },
  20453. enumerable: true,
  20454. configurable: true
  20455. });
  20456. Object.defineProperty(Scene.prototype, "fogMode", {
  20457. get: function () {
  20458. return this._fogMode;
  20459. },
  20460. set: function (value) {
  20461. if (this._fogMode === value) {
  20462. return;
  20463. }
  20464. this._fogMode = value;
  20465. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20466. },
  20467. enumerable: true,
  20468. configurable: true
  20469. });
  20470. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20471. get: function () {
  20472. return this._shadowsEnabled;
  20473. },
  20474. set: function (value) {
  20475. if (this._shadowsEnabled === value) {
  20476. return;
  20477. }
  20478. this._shadowsEnabled = value;
  20479. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20480. },
  20481. enumerable: true,
  20482. configurable: true
  20483. });
  20484. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20485. get: function () {
  20486. return this._lightsEnabled;
  20487. },
  20488. set: function (value) {
  20489. if (this._lightsEnabled === value) {
  20490. return;
  20491. }
  20492. this._lightsEnabled = value;
  20493. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20494. },
  20495. enumerable: true,
  20496. configurable: true
  20497. });
  20498. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20499. /** The default material used on meshes when no material is affected */
  20500. get: function () {
  20501. if (!this._defaultMaterial) {
  20502. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20503. }
  20504. return this._defaultMaterial;
  20505. },
  20506. /** The default material used on meshes when no material is affected */
  20507. set: function (value) {
  20508. this._defaultMaterial = value;
  20509. },
  20510. enumerable: true,
  20511. configurable: true
  20512. });
  20513. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20514. get: function () {
  20515. return this._texturesEnabled;
  20516. },
  20517. set: function (value) {
  20518. if (this._texturesEnabled === value) {
  20519. return;
  20520. }
  20521. this._texturesEnabled = value;
  20522. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20523. },
  20524. enumerable: true,
  20525. configurable: true
  20526. });
  20527. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20528. get: function () {
  20529. return this._skeletonsEnabled;
  20530. },
  20531. set: function (value) {
  20532. if (this._skeletonsEnabled === value) {
  20533. return;
  20534. }
  20535. this._skeletonsEnabled = value;
  20536. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20537. },
  20538. enumerable: true,
  20539. configurable: true
  20540. });
  20541. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20542. get: function () {
  20543. if (!this._postProcessRenderPipelineManager) {
  20544. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20545. }
  20546. return this._postProcessRenderPipelineManager;
  20547. },
  20548. enumerable: true,
  20549. configurable: true
  20550. });
  20551. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20552. get: function () {
  20553. if (!this._mainSoundTrack) {
  20554. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20555. }
  20556. return this._mainSoundTrack;
  20557. },
  20558. enumerable: true,
  20559. configurable: true
  20560. });
  20561. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20562. get: function () {
  20563. return this._alternateRendering;
  20564. },
  20565. enumerable: true,
  20566. configurable: true
  20567. });
  20568. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20569. get: function () {
  20570. return this._frustumPlanes;
  20571. },
  20572. enumerable: true,
  20573. configurable: true
  20574. });
  20575. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20576. /**
  20577. * Gets the current geometry buffer associated to the scene.
  20578. */
  20579. get: function () {
  20580. return this._geometryBufferRenderer;
  20581. },
  20582. /**
  20583. * Sets the current geometry buffer for the scene.
  20584. */
  20585. set: function (geometryBufferRenderer) {
  20586. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20587. this._geometryBufferRenderer = geometryBufferRenderer;
  20588. }
  20589. },
  20590. enumerable: true,
  20591. configurable: true
  20592. });
  20593. Object.defineProperty(Scene.prototype, "debugLayer", {
  20594. // Properties
  20595. get: function () {
  20596. if (!this._debugLayer) {
  20597. this._debugLayer = new BABYLON.DebugLayer(this);
  20598. }
  20599. return this._debugLayer;
  20600. },
  20601. enumerable: true,
  20602. configurable: true
  20603. });
  20604. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20605. get: function () {
  20606. return this._workerCollisions;
  20607. },
  20608. set: function (enabled) {
  20609. if (!BABYLON.CollisionCoordinatorLegacy) {
  20610. return;
  20611. }
  20612. enabled = (enabled && !!Worker);
  20613. this._workerCollisions = enabled;
  20614. if (this.collisionCoordinator) {
  20615. this.collisionCoordinator.destroy();
  20616. }
  20617. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20618. this.collisionCoordinator.init(this);
  20619. },
  20620. enumerable: true,
  20621. configurable: true
  20622. });
  20623. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20624. get: function () {
  20625. return this._selectionOctree;
  20626. },
  20627. enumerable: true,
  20628. configurable: true
  20629. });
  20630. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20631. /**
  20632. * The mesh that is currently under the pointer.
  20633. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20634. */
  20635. get: function () {
  20636. return this._pointerOverMesh;
  20637. },
  20638. enumerable: true,
  20639. configurable: true
  20640. });
  20641. Object.defineProperty(Scene.prototype, "pointerX", {
  20642. /**
  20643. * Current on-screen X position of the pointer
  20644. * @return {number} X position of the pointer
  20645. */
  20646. get: function () {
  20647. return this._pointerX;
  20648. },
  20649. enumerable: true,
  20650. configurable: true
  20651. });
  20652. Object.defineProperty(Scene.prototype, "pointerY", {
  20653. /**
  20654. * Current on-screen Y position of the pointer
  20655. * @return {number} Y position of the pointer
  20656. */
  20657. get: function () {
  20658. return this._pointerY;
  20659. },
  20660. enumerable: true,
  20661. configurable: true
  20662. });
  20663. Scene.prototype.getCachedMaterial = function () {
  20664. return this._cachedMaterial;
  20665. };
  20666. Scene.prototype.getCachedEffect = function () {
  20667. return this._cachedEffect;
  20668. };
  20669. Scene.prototype.getCachedVisibility = function () {
  20670. return this._cachedVisibility;
  20671. };
  20672. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20673. if (visibility === void 0) { visibility = 1; }
  20674. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20675. };
  20676. Scene.prototype.getBoundingBoxRenderer = function () {
  20677. if (!this._boundingBoxRenderer) {
  20678. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20679. }
  20680. return this._boundingBoxRenderer;
  20681. };
  20682. Scene.prototype.getOutlineRenderer = function () {
  20683. return this._outlineRenderer;
  20684. };
  20685. Scene.prototype.getEngine = function () {
  20686. return this._engine;
  20687. };
  20688. Scene.prototype.getTotalVertices = function () {
  20689. return this._totalVertices.current;
  20690. };
  20691. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20692. get: function () {
  20693. return this._totalVertices;
  20694. },
  20695. enumerable: true,
  20696. configurable: true
  20697. });
  20698. Scene.prototype.getActiveIndices = function () {
  20699. return this._activeIndices.current;
  20700. };
  20701. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20702. get: function () {
  20703. return this._activeIndices;
  20704. },
  20705. enumerable: true,
  20706. configurable: true
  20707. });
  20708. Scene.prototype.getActiveParticles = function () {
  20709. return this._activeParticles.current;
  20710. };
  20711. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20712. get: function () {
  20713. return this._activeParticles;
  20714. },
  20715. enumerable: true,
  20716. configurable: true
  20717. });
  20718. Scene.prototype.getActiveBones = function () {
  20719. return this._activeBones.current;
  20720. };
  20721. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20722. get: function () {
  20723. return this._activeBones;
  20724. },
  20725. enumerable: true,
  20726. configurable: true
  20727. });
  20728. // Stats
  20729. Scene.prototype.getInterFramePerfCounter = function () {
  20730. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20731. return 0;
  20732. };
  20733. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20734. get: function () {
  20735. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20736. return null;
  20737. },
  20738. enumerable: true,
  20739. configurable: true
  20740. });
  20741. Scene.prototype.getLastFrameDuration = function () {
  20742. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20743. return 0;
  20744. };
  20745. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20746. get: function () {
  20747. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20748. return null;
  20749. },
  20750. enumerable: true,
  20751. configurable: true
  20752. });
  20753. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20754. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20755. return 0;
  20756. };
  20757. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20758. get: function () {
  20759. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20760. return null;
  20761. },
  20762. enumerable: true,
  20763. configurable: true
  20764. });
  20765. Scene.prototype.getActiveMeshes = function () {
  20766. return this._activeMeshes;
  20767. };
  20768. Scene.prototype.getRenderTargetsDuration = function () {
  20769. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20770. return 0;
  20771. };
  20772. Scene.prototype.getRenderDuration = function () {
  20773. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20774. return 0;
  20775. };
  20776. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20777. get: function () {
  20778. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20779. return null;
  20780. },
  20781. enumerable: true,
  20782. configurable: true
  20783. });
  20784. Scene.prototype.getParticlesDuration = function () {
  20785. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20786. return 0;
  20787. };
  20788. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20789. get: function () {
  20790. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20791. return null;
  20792. },
  20793. enumerable: true,
  20794. configurable: true
  20795. });
  20796. Scene.prototype.getSpritesDuration = function () {
  20797. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20798. return 0;
  20799. };
  20800. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20801. get: function () {
  20802. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20803. return null;
  20804. },
  20805. enumerable: true,
  20806. configurable: true
  20807. });
  20808. Scene.prototype.getAnimationRatio = function () {
  20809. return this._animationRatio;
  20810. };
  20811. Scene.prototype.getRenderId = function () {
  20812. return this._renderId;
  20813. };
  20814. Scene.prototype.incrementRenderId = function () {
  20815. this._renderId++;
  20816. };
  20817. Scene.prototype._updatePointerPosition = function (evt) {
  20818. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20819. if (!canvasRect) {
  20820. return;
  20821. }
  20822. this._pointerX = evt.clientX - canvasRect.left;
  20823. this._pointerY = evt.clientY - canvasRect.top;
  20824. this._unTranslatedPointerX = this._pointerX;
  20825. this._unTranslatedPointerY = this._pointerY;
  20826. };
  20827. Scene.prototype._createUbo = function () {
  20828. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20829. this._sceneUbo.addUniform("viewProjection", 16);
  20830. this._sceneUbo.addUniform("view", 16);
  20831. };
  20832. Scene.prototype._createAlternateUbo = function () {
  20833. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20834. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20835. this._alternateSceneUbo.addUniform("view", 16);
  20836. };
  20837. // Pointers handling
  20838. /**
  20839. * Use this method to simulate a pointer move on a mesh
  20840. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20841. */
  20842. Scene.prototype.simulatePointerMove = function (pickResult) {
  20843. var evt = new PointerEvent("pointermove");
  20844. return this._processPointerMove(pickResult, evt);
  20845. };
  20846. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20847. var canvas = this._engine.getRenderingCanvas();
  20848. if (!canvas) {
  20849. return this;
  20850. }
  20851. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20852. this.setPointerOverSprite(null);
  20853. this.setPointerOverMesh(pickResult.pickedMesh);
  20854. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20855. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20856. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20857. }
  20858. else {
  20859. canvas.style.cursor = this.hoverCursor;
  20860. }
  20861. }
  20862. else {
  20863. canvas.style.cursor = this.defaultCursor;
  20864. }
  20865. }
  20866. else {
  20867. this.setPointerOverMesh(null);
  20868. // Sprites
  20869. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20870. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20871. this.setPointerOverSprite(pickResult.pickedSprite);
  20872. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20873. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20874. }
  20875. else {
  20876. canvas.style.cursor = this.hoverCursor;
  20877. }
  20878. }
  20879. else {
  20880. this.setPointerOverSprite(null);
  20881. // Restore pointer
  20882. canvas.style.cursor = this.defaultCursor;
  20883. }
  20884. }
  20885. if (pickResult) {
  20886. if (this.onPointerMove) {
  20887. this.onPointerMove(evt, pickResult);
  20888. }
  20889. if (this.onPointerObservable.hasObservers()) {
  20890. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20891. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20892. this.onPointerObservable.notifyObservers(pi, type);
  20893. }
  20894. }
  20895. return this;
  20896. };
  20897. /**
  20898. * Use this method to simulate a pointer down on a mesh
  20899. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20900. */
  20901. Scene.prototype.simulatePointerDown = function (pickResult) {
  20902. var evt = new PointerEvent("pointerdown");
  20903. return this._processPointerDown(pickResult, evt);
  20904. };
  20905. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20906. var _this = this;
  20907. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20908. this._pickedDownMesh = pickResult.pickedMesh;
  20909. var actionManager = pickResult.pickedMesh.actionManager;
  20910. if (actionManager) {
  20911. if (actionManager.hasPickTriggers) {
  20912. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20913. switch (evt.button) {
  20914. case 0:
  20915. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20916. break;
  20917. case 1:
  20918. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20919. break;
  20920. case 2:
  20921. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20922. break;
  20923. }
  20924. }
  20925. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20926. window.setTimeout(function () {
  20927. 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);
  20928. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20929. if (_this._totalPointersPressed !== 0 &&
  20930. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20931. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20932. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20933. _this._startingPointerTime = 0;
  20934. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20935. }
  20936. }
  20937. }, Scene.LongPressDelay);
  20938. }
  20939. }
  20940. }
  20941. if (pickResult) {
  20942. if (this.onPointerDown) {
  20943. this.onPointerDown(evt, pickResult);
  20944. }
  20945. if (this.onPointerObservable.hasObservers()) {
  20946. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20947. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20948. this.onPointerObservable.notifyObservers(pi, type);
  20949. }
  20950. }
  20951. return this;
  20952. };
  20953. /**
  20954. * Use this method to simulate a pointer up on a mesh
  20955. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20956. */
  20957. Scene.prototype.simulatePointerUp = function (pickResult) {
  20958. var evt = new PointerEvent("pointerup");
  20959. var clickInfo = new ClickInfo();
  20960. clickInfo.singleClick = true;
  20961. clickInfo.ignore = true;
  20962. return this._processPointerUp(pickResult, evt, clickInfo);
  20963. };
  20964. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20965. if (pickResult && pickResult && pickResult.pickedMesh) {
  20966. this._pickedUpMesh = pickResult.pickedMesh;
  20967. if (this._pickedDownMesh === this._pickedUpMesh) {
  20968. if (this.onPointerPick) {
  20969. this.onPointerPick(evt, pickResult);
  20970. }
  20971. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20972. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20973. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20974. this.onPointerObservable.notifyObservers(pi, type);
  20975. }
  20976. }
  20977. if (pickResult.pickedMesh.actionManager) {
  20978. if (clickInfo.ignore) {
  20979. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20980. }
  20981. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20982. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20983. }
  20984. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20985. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20986. }
  20987. }
  20988. }
  20989. if (this._pickedDownMesh &&
  20990. this._pickedDownMesh.actionManager &&
  20991. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20992. this._pickedDownMesh !== this._pickedUpMesh) {
  20993. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20994. }
  20995. if (this.onPointerUp) {
  20996. this.onPointerUp(evt, pickResult);
  20997. }
  20998. if (this.onPointerObservable.hasObservers()) {
  20999. if (!clickInfo.ignore) {
  21000. if (!clickInfo.hasSwiped) {
  21001. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21002. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21003. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21004. this.onPointerObservable.notifyObservers(pi, type);
  21005. }
  21006. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21007. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21008. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21009. this.onPointerObservable.notifyObservers(pi, type);
  21010. }
  21011. }
  21012. }
  21013. else {
  21014. var type = BABYLON.PointerEventTypes.POINTERUP;
  21015. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21016. this.onPointerObservable.notifyObservers(pi, type);
  21017. }
  21018. }
  21019. return this;
  21020. };
  21021. /**
  21022. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21023. * @param attachUp defines if you want to attach events to pointerup
  21024. * @param attachDown defines if you want to attach events to pointerdown
  21025. * @param attachMove defines if you want to attach events to pointermove
  21026. */
  21027. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21028. var _this = this;
  21029. if (attachUp === void 0) { attachUp = true; }
  21030. if (attachDown === void 0) { attachDown = true; }
  21031. if (attachMove === void 0) { attachMove = true; }
  21032. this._initActionManager = function (act, clickInfo) {
  21033. if (!_this._meshPickProceed) {
  21034. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21035. _this._currentPickResult = pickResult;
  21036. if (pickResult) {
  21037. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21038. }
  21039. _this._meshPickProceed = true;
  21040. }
  21041. return act;
  21042. };
  21043. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21044. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21045. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21046. btn !== _this._previousButtonPressed) {
  21047. _this._doubleClickOccured = false;
  21048. clickInfo.singleClick = true;
  21049. clickInfo.ignore = false;
  21050. cb(clickInfo, _this._currentPickResult);
  21051. }
  21052. };
  21053. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21054. var clickInfo = new ClickInfo();
  21055. _this._currentPickResult = null;
  21056. var act = null;
  21057. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21058. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21059. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21060. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21061. act = _this._initActionManager(act, clickInfo);
  21062. if (act)
  21063. checkPicking = act.hasPickTriggers;
  21064. }
  21065. if (checkPicking) {
  21066. var btn = evt.button;
  21067. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21068. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21069. if (!clickInfo.hasSwiped) {
  21070. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21071. if (!checkSingleClickImmediately) {
  21072. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21073. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21074. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21075. act = _this._initActionManager(act, clickInfo);
  21076. if (act)
  21077. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21078. }
  21079. }
  21080. if (checkSingleClickImmediately) {
  21081. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21082. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21083. btn !== _this._previousButtonPressed) {
  21084. clickInfo.singleClick = true;
  21085. cb(clickInfo, _this._currentPickResult);
  21086. }
  21087. }
  21088. else {
  21089. // wait that no double click has been raised during the double click delay
  21090. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21091. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21092. }
  21093. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21094. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21095. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21096. act = _this._initActionManager(act, clickInfo);
  21097. if (act)
  21098. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21099. }
  21100. if (checkDoubleClick) {
  21101. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21102. if (btn === _this._previousButtonPressed &&
  21103. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21104. !_this._doubleClickOccured) {
  21105. // pointer has not moved for 2 clicks, it's a double click
  21106. if (!clickInfo.hasSwiped &&
  21107. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21108. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21109. _this._previousStartingPointerTime = 0;
  21110. _this._doubleClickOccured = true;
  21111. clickInfo.doubleClick = true;
  21112. clickInfo.ignore = false;
  21113. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21114. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21115. }
  21116. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21117. cb(clickInfo, _this._currentPickResult);
  21118. }
  21119. else {
  21120. _this._doubleClickOccured = false;
  21121. _this._previousStartingPointerTime = _this._startingPointerTime;
  21122. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21123. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21124. _this._previousButtonPressed = btn;
  21125. if (Scene.ExclusiveDoubleClickMode) {
  21126. if (_this._previousDelayedSimpleClickTimeout) {
  21127. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21128. }
  21129. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21130. cb(clickInfo, _this._previousPickResult);
  21131. }
  21132. else {
  21133. cb(clickInfo, _this._currentPickResult);
  21134. }
  21135. }
  21136. }
  21137. else {
  21138. _this._doubleClickOccured = false;
  21139. _this._previousStartingPointerTime = _this._startingPointerTime;
  21140. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21141. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21142. _this._previousButtonPressed = btn;
  21143. }
  21144. }
  21145. }
  21146. }
  21147. clickInfo.ignore = true;
  21148. cb(clickInfo, _this._currentPickResult);
  21149. };
  21150. this._spritePredicate = function (sprite) {
  21151. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21152. };
  21153. this._onPointerMove = function (evt) {
  21154. _this._updatePointerPosition(evt);
  21155. // PreObservable support
  21156. if (_this.onPrePointerObservable.hasObservers()) {
  21157. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21158. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21159. _this.onPrePointerObservable.notifyObservers(pi, type);
  21160. if (pi.skipOnPointerObservable) {
  21161. return;
  21162. }
  21163. }
  21164. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21165. return;
  21166. }
  21167. if (!_this.pointerMovePredicate) {
  21168. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21169. }
  21170. // Meshes
  21171. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21172. _this._processPointerMove(pickResult, evt);
  21173. };
  21174. this._onPointerDown = function (evt) {
  21175. _this._totalPointersPressed++;
  21176. _this._pickedDownMesh = null;
  21177. _this._meshPickProceed = false;
  21178. _this._updatePointerPosition(evt);
  21179. if (_this.preventDefaultOnPointerDown && canvas) {
  21180. evt.preventDefault();
  21181. canvas.focus();
  21182. }
  21183. // PreObservable support
  21184. if (_this.onPrePointerObservable.hasObservers()) {
  21185. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21186. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21187. _this.onPrePointerObservable.notifyObservers(pi, type);
  21188. if (pi.skipOnPointerObservable) {
  21189. return;
  21190. }
  21191. }
  21192. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21193. return;
  21194. }
  21195. _this._startingPointerPosition.x = _this._pointerX;
  21196. _this._startingPointerPosition.y = _this._pointerY;
  21197. _this._startingPointerTime = new Date().getTime();
  21198. if (!_this.pointerDownPredicate) {
  21199. _this.pointerDownPredicate = function (mesh) {
  21200. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21201. };
  21202. }
  21203. // Meshes
  21204. _this._pickedDownMesh = null;
  21205. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21206. _this._processPointerDown(pickResult, evt);
  21207. // Sprites
  21208. _this._pickedDownSprite = null;
  21209. if (_this.spriteManagers.length > 0) {
  21210. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21211. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21212. if (pickResult.pickedSprite.actionManager) {
  21213. _this._pickedDownSprite = pickResult.pickedSprite;
  21214. switch (evt.button) {
  21215. case 0:
  21216. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21217. break;
  21218. case 1:
  21219. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21220. break;
  21221. case 2:
  21222. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21223. break;
  21224. }
  21225. if (pickResult.pickedSprite.actionManager) {
  21226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21227. }
  21228. }
  21229. }
  21230. }
  21231. };
  21232. this._onPointerUp = function (evt) {
  21233. if (_this._totalPointersPressed === 0) {
  21234. return; // So we need to test it the pointer down was pressed before.
  21235. }
  21236. _this._totalPointersPressed--;
  21237. _this._pickedUpMesh = null;
  21238. _this._meshPickProceed = false;
  21239. _this._updatePointerPosition(evt);
  21240. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21241. // PreObservable support
  21242. if (_this.onPrePointerObservable.hasObservers()) {
  21243. if (!clickInfo.ignore) {
  21244. if (!clickInfo.hasSwiped) {
  21245. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21246. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21247. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21248. _this.onPrePointerObservable.notifyObservers(pi, type);
  21249. if (pi.skipOnPointerObservable) {
  21250. return;
  21251. }
  21252. }
  21253. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21254. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21255. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21256. _this.onPrePointerObservable.notifyObservers(pi, type);
  21257. if (pi.skipOnPointerObservable) {
  21258. return;
  21259. }
  21260. }
  21261. }
  21262. }
  21263. else {
  21264. var type = BABYLON.PointerEventTypes.POINTERUP;
  21265. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21266. _this.onPrePointerObservable.notifyObservers(pi, type);
  21267. if (pi.skipOnPointerObservable) {
  21268. return;
  21269. }
  21270. }
  21271. }
  21272. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21273. return;
  21274. }
  21275. if (!_this.pointerUpPredicate) {
  21276. _this.pointerUpPredicate = function (mesh) {
  21277. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21278. };
  21279. }
  21280. // Meshes
  21281. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21282. _this._initActionManager(null, clickInfo);
  21283. }
  21284. if (!pickResult) {
  21285. pickResult = _this._currentPickResult;
  21286. }
  21287. _this._processPointerUp(pickResult, evt, clickInfo);
  21288. // Sprites
  21289. if (_this.spriteManagers.length > 0) {
  21290. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21291. if (spritePickResult) {
  21292. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21293. if (spritePickResult.pickedSprite.actionManager) {
  21294. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21295. if (spritePickResult.pickedSprite.actionManager) {
  21296. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21297. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21298. }
  21299. }
  21300. }
  21301. }
  21302. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21303. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21304. }
  21305. }
  21306. }
  21307. _this._previousPickResult = _this._currentPickResult;
  21308. });
  21309. };
  21310. this._onKeyDown = function (evt) {
  21311. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21312. if (_this.onPreKeyboardObservable.hasObservers()) {
  21313. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21314. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21315. if (pi.skipOnPointerObservable) {
  21316. return;
  21317. }
  21318. }
  21319. if (_this.onKeyboardObservable.hasObservers()) {
  21320. var pi = new BABYLON.KeyboardInfo(type, evt);
  21321. _this.onKeyboardObservable.notifyObservers(pi, type);
  21322. }
  21323. if (_this.actionManager) {
  21324. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21325. }
  21326. };
  21327. this._onKeyUp = function (evt) {
  21328. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21329. if (_this.onPreKeyboardObservable.hasObservers()) {
  21330. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21331. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21332. if (pi.skipOnPointerObservable) {
  21333. return;
  21334. }
  21335. }
  21336. if (_this.onKeyboardObservable.hasObservers()) {
  21337. var pi = new BABYLON.KeyboardInfo(type, evt);
  21338. _this.onKeyboardObservable.notifyObservers(pi, type);
  21339. }
  21340. if (_this.actionManager) {
  21341. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21342. }
  21343. };
  21344. var engine = this.getEngine();
  21345. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21346. if (!canvas) {
  21347. return;
  21348. }
  21349. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21350. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21351. });
  21352. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21353. if (!canvas) {
  21354. return;
  21355. }
  21356. canvas.removeEventListener("keydown", _this._onKeyDown);
  21357. canvas.removeEventListener("keyup", _this._onKeyUp);
  21358. });
  21359. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21360. var canvas = this._engine.getRenderingCanvas();
  21361. if (!canvas) {
  21362. return;
  21363. }
  21364. if (attachMove) {
  21365. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21366. // Wheel
  21367. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21368. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21369. }
  21370. if (attachDown) {
  21371. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21372. }
  21373. if (attachUp) {
  21374. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21375. }
  21376. canvas.tabIndex = 1;
  21377. };
  21378. Scene.prototype.detachControl = function () {
  21379. var engine = this.getEngine();
  21380. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21381. var canvas = engine.getRenderingCanvas();
  21382. if (!canvas) {
  21383. return;
  21384. }
  21385. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21386. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21387. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21388. if (this._onCanvasBlurObserver) {
  21389. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21390. }
  21391. if (this._onCanvasFocusObserver) {
  21392. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21393. }
  21394. // Wheel
  21395. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21396. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21397. // Keyboard
  21398. canvas.removeEventListener("keydown", this._onKeyDown);
  21399. canvas.removeEventListener("keyup", this._onKeyUp);
  21400. // Observables
  21401. this.onKeyboardObservable.clear();
  21402. this.onPreKeyboardObservable.clear();
  21403. this.onPointerObservable.clear();
  21404. this.onPrePointerObservable.clear();
  21405. };
  21406. /**
  21407. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21408. * Delay loaded resources are not taking in account
  21409. * @return true if all required resources are ready
  21410. */
  21411. Scene.prototype.isReady = function () {
  21412. if (this._isDisposed) {
  21413. return false;
  21414. }
  21415. if (this._pendingData.length > 0) {
  21416. return false;
  21417. }
  21418. var index;
  21419. var engine = this.getEngine();
  21420. // Geometries
  21421. for (index = 0; index < this._geometries.length; index++) {
  21422. var geometry = this._geometries[index];
  21423. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21424. return false;
  21425. }
  21426. }
  21427. // Meshes
  21428. for (index = 0; index < this.meshes.length; index++) {
  21429. var mesh = this.meshes[index];
  21430. if (!mesh.isEnabled()) {
  21431. continue;
  21432. }
  21433. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21434. continue;
  21435. }
  21436. if (!mesh.isReady()) {
  21437. return false;
  21438. }
  21439. // Highlight layers
  21440. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21441. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21442. var layer = _a[_i];
  21443. if (!layer.hasMesh(mesh)) {
  21444. continue;
  21445. }
  21446. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21447. var subMesh = _c[_b];
  21448. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21449. return false;
  21450. }
  21451. }
  21452. }
  21453. }
  21454. return true;
  21455. };
  21456. Scene.prototype.resetCachedMaterial = function () {
  21457. this._cachedMaterial = null;
  21458. this._cachedEffect = null;
  21459. this._cachedVisibility = null;
  21460. };
  21461. Scene.prototype.registerBeforeRender = function (func) {
  21462. this.onBeforeRenderObservable.add(func);
  21463. };
  21464. Scene.prototype.unregisterBeforeRender = function (func) {
  21465. this.onBeforeRenderObservable.removeCallback(func);
  21466. };
  21467. Scene.prototype.registerAfterRender = function (func) {
  21468. this.onAfterRenderObservable.add(func);
  21469. };
  21470. Scene.prototype.unregisterAfterRender = function (func) {
  21471. this.onAfterRenderObservable.removeCallback(func);
  21472. };
  21473. Scene.prototype._executeOnceBeforeRender = function (func) {
  21474. var _this = this;
  21475. var execFunc = function () {
  21476. func();
  21477. setTimeout(function () {
  21478. _this.unregisterBeforeRender(execFunc);
  21479. });
  21480. };
  21481. this.registerBeforeRender(execFunc);
  21482. };
  21483. /**
  21484. * The provided function will run before render once and will be disposed afterwards.
  21485. * A timeout delay can be provided so that the function will be executed in N ms.
  21486. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21487. * @param func The function to be executed.
  21488. * @param timeout optional delay in ms
  21489. */
  21490. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21491. var _this = this;
  21492. if (timeout !== undefined) {
  21493. setTimeout(function () {
  21494. _this._executeOnceBeforeRender(func);
  21495. }, timeout);
  21496. }
  21497. else {
  21498. this._executeOnceBeforeRender(func);
  21499. }
  21500. };
  21501. Scene.prototype._addPendingData = function (data) {
  21502. this._pendingData.push(data);
  21503. };
  21504. Scene.prototype._removePendingData = function (data) {
  21505. var wasLoading = this.isLoading;
  21506. var index = this._pendingData.indexOf(data);
  21507. if (index !== -1) {
  21508. this._pendingData.splice(index, 1);
  21509. }
  21510. if (wasLoading && !this.isLoading) {
  21511. this.onDataLoadedObservable.notifyObservers(this);
  21512. }
  21513. };
  21514. Scene.prototype.getWaitingItemsCount = function () {
  21515. return this._pendingData.length;
  21516. };
  21517. Object.defineProperty(Scene.prototype, "isLoading", {
  21518. get: function () {
  21519. return this._pendingData.length > 0;
  21520. },
  21521. enumerable: true,
  21522. configurable: true
  21523. });
  21524. /**
  21525. * Registers a function to be executed when the scene is ready.
  21526. * @param {Function} func - the function to be executed.
  21527. */
  21528. Scene.prototype.executeWhenReady = function (func) {
  21529. var _this = this;
  21530. this.onReadyObservable.add(func);
  21531. if (this._executeWhenReadyTimeoutId !== -1) {
  21532. return;
  21533. }
  21534. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21535. _this._checkIsReady();
  21536. }, 150);
  21537. };
  21538. Scene.prototype._checkIsReady = function () {
  21539. var _this = this;
  21540. if (this.isReady()) {
  21541. this.onReadyObservable.notifyObservers(this);
  21542. this.onReadyObservable.clear();
  21543. this._executeWhenReadyTimeoutId = -1;
  21544. return;
  21545. }
  21546. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21547. _this._checkIsReady();
  21548. }, 150);
  21549. };
  21550. // Animations
  21551. /**
  21552. * Will start the animation sequence of a given target
  21553. * @param target - the target
  21554. * @param {number} from - from which frame should animation start
  21555. * @param {number} to - till which frame should animation run.
  21556. * @param {boolean} [loop] - should the animation loop
  21557. * @param {number} [speedRatio] - the speed in which to run the animation
  21558. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21559. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21560. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21561. * See BABYLON.Animatable
  21562. */
  21563. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21564. if (speedRatio === void 0) { speedRatio = 1.0; }
  21565. if (from > to && speedRatio > 0) {
  21566. speedRatio *= -1;
  21567. }
  21568. this.stopAnimation(target);
  21569. if (!animatable) {
  21570. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21571. }
  21572. // Local animations
  21573. if (target.animations) {
  21574. animatable.appendAnimations(target, target.animations);
  21575. }
  21576. // Children animations
  21577. if (target.getAnimatables) {
  21578. var animatables = target.getAnimatables();
  21579. for (var index = 0; index < animatables.length; index++) {
  21580. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21581. }
  21582. }
  21583. animatable.reset();
  21584. return animatable;
  21585. };
  21586. /**
  21587. * Begin a new animation on a given node
  21588. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21589. * @param {BABYLON.Animation[]} defines the list of animations to start
  21590. * @param {number} from defines the initial value
  21591. * @param {number} to defines the final value
  21592. * @param {boolean} loop defines if you want animation to loop (off by default)
  21593. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21594. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21595. * @returns the list of created animatables
  21596. */
  21597. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21598. if (speedRatio === undefined) {
  21599. speedRatio = 1.0;
  21600. }
  21601. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21602. return animatable;
  21603. };
  21604. /**
  21605. * Begin a new animation on a given node and its hierarchy
  21606. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21607. * @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.
  21608. * @param {BABYLON.Animation[]} defines the list of animations to start
  21609. * @param {number} from defines the initial value
  21610. * @param {number} to defines the final value
  21611. * @param {boolean} loop defines if you want animation to loop (off by default)
  21612. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21613. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21614. * @returns the list of animatables created for all nodes
  21615. */
  21616. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21617. var children = target.getDescendants(directDescendantsOnly);
  21618. var result = [];
  21619. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21620. var child = children_1[_i];
  21621. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21622. }
  21623. return result;
  21624. };
  21625. Scene.prototype.getAnimatableByTarget = function (target) {
  21626. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21627. if (this._activeAnimatables[index].target === target) {
  21628. return this._activeAnimatables[index];
  21629. }
  21630. }
  21631. return null;
  21632. };
  21633. Object.defineProperty(Scene.prototype, "animatables", {
  21634. get: function () {
  21635. return this._activeAnimatables;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. /**
  21641. * Will stop the animation of the given target
  21642. * @param target - the target
  21643. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21644. * @see beginAnimation
  21645. */
  21646. Scene.prototype.stopAnimation = function (target, animationName) {
  21647. var animatable = this.getAnimatableByTarget(target);
  21648. if (animatable) {
  21649. animatable.stop(animationName);
  21650. }
  21651. };
  21652. /**
  21653. * Stops and removes all animations that have been applied to the scene
  21654. */
  21655. Scene.prototype.stopAllAnimations = function () {
  21656. if (this._activeAnimatables) {
  21657. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21658. this._activeAnimatables[i].stop();
  21659. }
  21660. this._activeAnimatables = [];
  21661. }
  21662. };
  21663. Scene.prototype._animate = function () {
  21664. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21665. return;
  21666. }
  21667. // Getting time
  21668. var now = BABYLON.Tools.Now;
  21669. if (!this._animationTimeLast) {
  21670. if (this._pendingData.length > 0) {
  21671. return;
  21672. }
  21673. this._animationTimeLast = now;
  21674. }
  21675. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21676. this._animationTime += deltaTime;
  21677. this._animationTimeLast = now;
  21678. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21679. this._activeAnimatables[index]._animate(this._animationTime);
  21680. }
  21681. };
  21682. // Matrix
  21683. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21684. this._useAlternateCameraConfiguration = active;
  21685. };
  21686. Scene.prototype.getViewMatrix = function () {
  21687. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21688. };
  21689. Scene.prototype.getProjectionMatrix = function () {
  21690. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21691. };
  21692. Scene.prototype.getTransformMatrix = function () {
  21693. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21694. };
  21695. Scene.prototype.setTransformMatrix = function (view, projection) {
  21696. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21697. return;
  21698. }
  21699. this._viewUpdateFlag = view.updateFlag;
  21700. this._projectionUpdateFlag = projection.updateFlag;
  21701. this._viewMatrix = view;
  21702. this._projectionMatrix = projection;
  21703. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21704. // Update frustum
  21705. if (!this._frustumPlanes) {
  21706. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21707. }
  21708. else {
  21709. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21710. }
  21711. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21712. var otherCamera = this.activeCamera._alternateCamera;
  21713. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21714. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21715. }
  21716. if (this._sceneUbo.useUbo) {
  21717. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21718. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21719. this._sceneUbo.update();
  21720. }
  21721. };
  21722. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21723. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21724. return;
  21725. }
  21726. this._alternateViewUpdateFlag = view.updateFlag;
  21727. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21728. this._alternateViewMatrix = view;
  21729. this._alternateProjectionMatrix = projection;
  21730. if (!this._alternateTransformMatrix) {
  21731. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21732. }
  21733. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21734. if (!this._alternateSceneUbo) {
  21735. this._createAlternateUbo();
  21736. }
  21737. if (this._alternateSceneUbo.useUbo) {
  21738. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21739. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21740. this._alternateSceneUbo.update();
  21741. }
  21742. };
  21743. Scene.prototype.getSceneUniformBuffer = function () {
  21744. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21745. };
  21746. // Methods
  21747. Scene.prototype.getUniqueId = function () {
  21748. var result = Scene._uniqueIdCounter;
  21749. Scene._uniqueIdCounter++;
  21750. return result;
  21751. };
  21752. Scene.prototype.addMesh = function (newMesh) {
  21753. this.meshes.push(newMesh);
  21754. //notify the collision coordinator
  21755. if (this.collisionCoordinator) {
  21756. this.collisionCoordinator.onMeshAdded(newMesh);
  21757. }
  21758. newMesh._resyncLightSources();
  21759. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21760. };
  21761. Scene.prototype.removeMesh = function (toRemove) {
  21762. var index = this.meshes.indexOf(toRemove);
  21763. if (index !== -1) {
  21764. // Remove from the scene if mesh found
  21765. this.meshes.splice(index, 1);
  21766. }
  21767. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21768. return index;
  21769. };
  21770. Scene.prototype.addTransformNode = function (newTransformNode) {
  21771. this.transformNodes.push(newTransformNode);
  21772. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21773. };
  21774. Scene.prototype.removeTransformNode = function (toRemove) {
  21775. var index = this.transformNodes.indexOf(toRemove);
  21776. if (index !== -1) {
  21777. // Remove from the scene if found
  21778. this.transformNodes.splice(index, 1);
  21779. }
  21780. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21781. return index;
  21782. };
  21783. Scene.prototype.removeSkeleton = function (toRemove) {
  21784. var index = this.skeletons.indexOf(toRemove);
  21785. if (index !== -1) {
  21786. // Remove from the scene if found
  21787. this.skeletons.splice(index, 1);
  21788. }
  21789. return index;
  21790. };
  21791. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21792. var index = this.morphTargetManagers.indexOf(toRemove);
  21793. if (index !== -1) {
  21794. // Remove from the scene if found
  21795. this.morphTargetManagers.splice(index, 1);
  21796. }
  21797. return index;
  21798. };
  21799. Scene.prototype.removeLight = function (toRemove) {
  21800. var index = this.lights.indexOf(toRemove);
  21801. if (index !== -1) {
  21802. // Remove from meshes
  21803. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21804. var mesh = _a[_i];
  21805. mesh._removeLightSource(toRemove);
  21806. }
  21807. // Remove from the scene if mesh found
  21808. this.lights.splice(index, 1);
  21809. this.sortLightsByPriority();
  21810. }
  21811. this.onLightRemovedObservable.notifyObservers(toRemove);
  21812. return index;
  21813. };
  21814. Scene.prototype.removeCamera = function (toRemove) {
  21815. var index = this.cameras.indexOf(toRemove);
  21816. if (index !== -1) {
  21817. // Remove from the scene if mesh found
  21818. this.cameras.splice(index, 1);
  21819. }
  21820. // Remove from activeCameras
  21821. var index2 = this.activeCameras.indexOf(toRemove);
  21822. if (index2 !== -1) {
  21823. // Remove from the scene if mesh found
  21824. this.activeCameras.splice(index2, 1);
  21825. }
  21826. // Reset the activeCamera
  21827. if (this.activeCamera === toRemove) {
  21828. if (this.cameras.length > 0) {
  21829. this.activeCamera = this.cameras[0];
  21830. }
  21831. else {
  21832. this.activeCamera = null;
  21833. }
  21834. }
  21835. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21836. return index;
  21837. };
  21838. Scene.prototype.removeParticleSystem = function (toRemove) {
  21839. var index = this.particleSystems.indexOf(toRemove);
  21840. if (index !== -1) {
  21841. this.particleSystems.splice(index, 1);
  21842. }
  21843. return index;
  21844. };
  21845. ;
  21846. Scene.prototype.removeAnimation = function (toRemove) {
  21847. var index = this.animations.indexOf(toRemove);
  21848. if (index !== -1) {
  21849. this.animations.splice(index, 1);
  21850. }
  21851. return index;
  21852. };
  21853. ;
  21854. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21855. var index = this.multiMaterials.indexOf(toRemove);
  21856. if (index !== -1) {
  21857. this.multiMaterials.splice(index, 1);
  21858. }
  21859. return index;
  21860. };
  21861. ;
  21862. Scene.prototype.removeMaterial = function (toRemove) {
  21863. var index = this.materials.indexOf(toRemove);
  21864. if (index !== -1) {
  21865. this.materials.splice(index, 1);
  21866. }
  21867. return index;
  21868. };
  21869. ;
  21870. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21871. var index = this.lensFlareSystems.indexOf(toRemove);
  21872. if (index !== -1) {
  21873. this.lensFlareSystems.splice(index, 1);
  21874. }
  21875. return index;
  21876. };
  21877. ;
  21878. Scene.prototype.removeActionManager = function (toRemove) {
  21879. var index = this._actionManagers.indexOf(toRemove);
  21880. if (index !== -1) {
  21881. this._actionManagers.splice(index, 1);
  21882. }
  21883. return index;
  21884. };
  21885. ;
  21886. Scene.prototype.addLight = function (newLight) {
  21887. this.lights.push(newLight);
  21888. this.sortLightsByPriority();
  21889. // Add light to all meshes (To support if the light is removed and then readded)
  21890. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21891. var mesh = _a[_i];
  21892. if (mesh._lightSources.indexOf(newLight) === -1) {
  21893. mesh._lightSources.push(newLight);
  21894. mesh._resyncLightSources();
  21895. }
  21896. }
  21897. this.onNewLightAddedObservable.notifyObservers(newLight);
  21898. };
  21899. Scene.prototype.sortLightsByPriority = function () {
  21900. if (this.requireLightSorting) {
  21901. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  21902. }
  21903. };
  21904. Scene.prototype.addCamera = function (newCamera) {
  21905. this.cameras.push(newCamera);
  21906. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21907. };
  21908. Scene.prototype.addSkeleton = function (newSkeleton) {
  21909. this.skeletons.push(newSkeleton);
  21910. };
  21911. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21912. this.particleSystems.push(newParticleSystem);
  21913. };
  21914. Scene.prototype.addAnimation = function (newAnimation) {
  21915. this.animations.push(newAnimation);
  21916. };
  21917. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21918. this.multiMaterials.push(newMultiMaterial);
  21919. };
  21920. Scene.prototype.addMaterial = function (newMaterial) {
  21921. this.materials.push(newMaterial);
  21922. };
  21923. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21924. this.morphTargetManagers.push(newMorphTargetManager);
  21925. };
  21926. Scene.prototype.addGeometry = function (newGeometrie) {
  21927. this._geometries.push(newGeometrie);
  21928. };
  21929. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21930. this.lensFlareSystems.push(newLensFlareSystem);
  21931. };
  21932. Scene.prototype.addActionManager = function (newActionManager) {
  21933. this._actionManagers.push(newActionManager);
  21934. };
  21935. /**
  21936. * Switch active camera
  21937. * @param {Camera} newCamera - new active camera
  21938. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21939. */
  21940. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21941. if (attachControl === void 0) { attachControl = true; }
  21942. var canvas = this._engine.getRenderingCanvas();
  21943. if (!canvas) {
  21944. return;
  21945. }
  21946. if (this.activeCamera) {
  21947. this.activeCamera.detachControl(canvas);
  21948. }
  21949. this.activeCamera = newCamera;
  21950. if (attachControl) {
  21951. newCamera.attachControl(canvas);
  21952. }
  21953. };
  21954. /**
  21955. * sets the active camera of the scene using its ID
  21956. * @param {string} id - the camera's ID
  21957. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21958. * @see activeCamera
  21959. */
  21960. Scene.prototype.setActiveCameraByID = function (id) {
  21961. var camera = this.getCameraByID(id);
  21962. if (camera) {
  21963. this.activeCamera = camera;
  21964. return camera;
  21965. }
  21966. return null;
  21967. };
  21968. /**
  21969. * sets the active camera of the scene using its name
  21970. * @param {string} name - the camera's name
  21971. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21972. * @see activeCamera
  21973. */
  21974. Scene.prototype.setActiveCameraByName = function (name) {
  21975. var camera = this.getCameraByName(name);
  21976. if (camera) {
  21977. this.activeCamera = camera;
  21978. return camera;
  21979. }
  21980. return null;
  21981. };
  21982. /**
  21983. * get an animation group using its name
  21984. * @param {string} the material's name
  21985. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21986. */
  21987. Scene.prototype.getAnimationGroupByName = function (name) {
  21988. for (var index = 0; index < this.animationGroups.length; index++) {
  21989. if (this.animationGroups[index].name === name) {
  21990. return this.animationGroups[index];
  21991. }
  21992. }
  21993. return null;
  21994. };
  21995. /**
  21996. * get a material using its id
  21997. * @param {string} the material's ID
  21998. * @return {BABYLON.Material|null} the material or null if none found.
  21999. */
  22000. Scene.prototype.getMaterialByID = function (id) {
  22001. for (var index = 0; index < this.materials.length; index++) {
  22002. if (this.materials[index].id === id) {
  22003. return this.materials[index];
  22004. }
  22005. }
  22006. return null;
  22007. };
  22008. /**
  22009. * get a material using its name
  22010. * @param {string} the material's name
  22011. * @return {BABYLON.Material|null} the material or null if none found.
  22012. */
  22013. Scene.prototype.getMaterialByName = function (name) {
  22014. for (var index = 0; index < this.materials.length; index++) {
  22015. if (this.materials[index].name === name) {
  22016. return this.materials[index];
  22017. }
  22018. }
  22019. return null;
  22020. };
  22021. Scene.prototype.getLensFlareSystemByName = function (name) {
  22022. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22023. if (this.lensFlareSystems[index].name === name) {
  22024. return this.lensFlareSystems[index];
  22025. }
  22026. }
  22027. return null;
  22028. };
  22029. Scene.prototype.getLensFlareSystemByID = function (id) {
  22030. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22031. if (this.lensFlareSystems[index].id === id) {
  22032. return this.lensFlareSystems[index];
  22033. }
  22034. }
  22035. return null;
  22036. };
  22037. Scene.prototype.getCameraByID = function (id) {
  22038. for (var index = 0; index < this.cameras.length; index++) {
  22039. if (this.cameras[index].id === id) {
  22040. return this.cameras[index];
  22041. }
  22042. }
  22043. return null;
  22044. };
  22045. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22046. for (var index = 0; index < this.cameras.length; index++) {
  22047. if (this.cameras[index].uniqueId === uniqueId) {
  22048. return this.cameras[index];
  22049. }
  22050. }
  22051. return null;
  22052. };
  22053. /**
  22054. * get a camera using its name
  22055. * @param {string} the camera's name
  22056. * @return {BABYLON.Camera|null} the camera or null if none found.
  22057. */
  22058. Scene.prototype.getCameraByName = function (name) {
  22059. for (var index = 0; index < this.cameras.length; index++) {
  22060. if (this.cameras[index].name === name) {
  22061. return this.cameras[index];
  22062. }
  22063. }
  22064. return null;
  22065. };
  22066. /**
  22067. * get a bone using its id
  22068. * @param {string} the bone's id
  22069. * @return {BABYLON.Bone|null} the bone or null if not found
  22070. */
  22071. Scene.prototype.getBoneByID = function (id) {
  22072. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22073. var skeleton = this.skeletons[skeletonIndex];
  22074. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22075. if (skeleton.bones[boneIndex].id === id) {
  22076. return skeleton.bones[boneIndex];
  22077. }
  22078. }
  22079. }
  22080. return null;
  22081. };
  22082. /**
  22083. * get a bone using its id
  22084. * @param {string} the bone's name
  22085. * @return {BABYLON.Bone|null} the bone or null if not found
  22086. */
  22087. Scene.prototype.getBoneByName = function (name) {
  22088. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22089. var skeleton = this.skeletons[skeletonIndex];
  22090. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22091. if (skeleton.bones[boneIndex].name === name) {
  22092. return skeleton.bones[boneIndex];
  22093. }
  22094. }
  22095. }
  22096. return null;
  22097. };
  22098. /**
  22099. * get a light node using its name
  22100. * @param {string} the light's name
  22101. * @return {BABYLON.Light|null} the light or null if none found.
  22102. */
  22103. Scene.prototype.getLightByName = function (name) {
  22104. for (var index = 0; index < this.lights.length; index++) {
  22105. if (this.lights[index].name === name) {
  22106. return this.lights[index];
  22107. }
  22108. }
  22109. return null;
  22110. };
  22111. /**
  22112. * get a light node using its ID
  22113. * @param {string} the light's id
  22114. * @return {BABYLON.Light|null} the light or null if none found.
  22115. */
  22116. Scene.prototype.getLightByID = function (id) {
  22117. for (var index = 0; index < this.lights.length; index++) {
  22118. if (this.lights[index].id === id) {
  22119. return this.lights[index];
  22120. }
  22121. }
  22122. return null;
  22123. };
  22124. /**
  22125. * get a light node using its scene-generated unique ID
  22126. * @param {number} the light's unique id
  22127. * @return {BABYLON.Light|null} the light or null if none found.
  22128. */
  22129. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22130. for (var index = 0; index < this.lights.length; index++) {
  22131. if (this.lights[index].uniqueId === uniqueId) {
  22132. return this.lights[index];
  22133. }
  22134. }
  22135. return null;
  22136. };
  22137. /**
  22138. * get a particle system by id
  22139. * @param id {number} the particle system id
  22140. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22141. */
  22142. Scene.prototype.getParticleSystemByID = function (id) {
  22143. for (var index = 0; index < this.particleSystems.length; index++) {
  22144. if (this.particleSystems[index].id === id) {
  22145. return this.particleSystems[index];
  22146. }
  22147. }
  22148. return null;
  22149. };
  22150. /**
  22151. * get a geometry using its ID
  22152. * @param {string} the geometry's id
  22153. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22154. */
  22155. Scene.prototype.getGeometryByID = function (id) {
  22156. for (var index = 0; index < this._geometries.length; index++) {
  22157. if (this._geometries[index].id === id) {
  22158. return this._geometries[index];
  22159. }
  22160. }
  22161. return null;
  22162. };
  22163. /**
  22164. * add a new geometry to this scene.
  22165. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22166. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22167. * @return {boolean} was the geometry added or not
  22168. */
  22169. Scene.prototype.pushGeometry = function (geometry, force) {
  22170. if (!force && this.getGeometryByID(geometry.id)) {
  22171. return false;
  22172. }
  22173. this._geometries.push(geometry);
  22174. //notify the collision coordinator
  22175. if (this.collisionCoordinator) {
  22176. this.collisionCoordinator.onGeometryAdded(geometry);
  22177. }
  22178. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22179. return true;
  22180. };
  22181. /**
  22182. * Removes an existing geometry
  22183. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22184. * @return {boolean} was the geometry removed or not
  22185. */
  22186. Scene.prototype.removeGeometry = function (geometry) {
  22187. var index = this._geometries.indexOf(geometry);
  22188. if (index > -1) {
  22189. this._geometries.splice(index, 1);
  22190. //notify the collision coordinator
  22191. if (this.collisionCoordinator) {
  22192. this.collisionCoordinator.onGeometryDeleted(geometry);
  22193. }
  22194. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22195. return true;
  22196. }
  22197. return false;
  22198. };
  22199. Scene.prototype.getGeometries = function () {
  22200. return this._geometries;
  22201. };
  22202. /**
  22203. * Get the first added mesh found of a given ID
  22204. * @param {string} id - the id to search for
  22205. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22206. */
  22207. Scene.prototype.getMeshByID = function (id) {
  22208. for (var index = 0; index < this.meshes.length; index++) {
  22209. if (this.meshes[index].id === id) {
  22210. return this.meshes[index];
  22211. }
  22212. }
  22213. return null;
  22214. };
  22215. Scene.prototype.getMeshesByID = function (id) {
  22216. return this.meshes.filter(function (m) {
  22217. return m.id === id;
  22218. });
  22219. };
  22220. /**
  22221. * Get the first added transform node found of a given ID
  22222. * @param {string} id - the id to search for
  22223. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22224. */
  22225. Scene.prototype.getTransformNodeByID = function (id) {
  22226. for (var index = 0; index < this.transformNodes.length; index++) {
  22227. if (this.transformNodes[index].id === id) {
  22228. return this.transformNodes[index];
  22229. }
  22230. }
  22231. return null;
  22232. };
  22233. Scene.prototype.getTransformNodesByID = function (id) {
  22234. return this.transformNodes.filter(function (m) {
  22235. return m.id === id;
  22236. });
  22237. };
  22238. /**
  22239. * Get a mesh with its auto-generated unique id
  22240. * @param {number} uniqueId - the unique id to search for
  22241. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22242. */
  22243. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22244. for (var index = 0; index < this.meshes.length; index++) {
  22245. if (this.meshes[index].uniqueId === uniqueId) {
  22246. return this.meshes[index];
  22247. }
  22248. }
  22249. return null;
  22250. };
  22251. /**
  22252. * Get a the last added mesh found of a given ID
  22253. * @param {string} id - the id to search for
  22254. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22255. */
  22256. Scene.prototype.getLastMeshByID = function (id) {
  22257. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22258. if (this.meshes[index].id === id) {
  22259. return this.meshes[index];
  22260. }
  22261. }
  22262. return null;
  22263. };
  22264. /**
  22265. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22266. * @param {string} id - the id to search for
  22267. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22268. */
  22269. Scene.prototype.getLastEntryByID = function (id) {
  22270. var index;
  22271. for (index = this.meshes.length - 1; index >= 0; index--) {
  22272. if (this.meshes[index].id === id) {
  22273. return this.meshes[index];
  22274. }
  22275. }
  22276. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22277. if (this.transformNodes[index].id === id) {
  22278. return this.transformNodes[index];
  22279. }
  22280. }
  22281. for (index = this.cameras.length - 1; index >= 0; index--) {
  22282. if (this.cameras[index].id === id) {
  22283. return this.cameras[index];
  22284. }
  22285. }
  22286. for (index = this.lights.length - 1; index >= 0; index--) {
  22287. if (this.lights[index].id === id) {
  22288. return this.lights[index];
  22289. }
  22290. }
  22291. return null;
  22292. };
  22293. Scene.prototype.getNodeByID = function (id) {
  22294. var mesh = this.getMeshByID(id);
  22295. if (mesh) {
  22296. return mesh;
  22297. }
  22298. var light = this.getLightByID(id);
  22299. if (light) {
  22300. return light;
  22301. }
  22302. var camera = this.getCameraByID(id);
  22303. if (camera) {
  22304. return camera;
  22305. }
  22306. var bone = this.getBoneByID(id);
  22307. return bone;
  22308. };
  22309. Scene.prototype.getNodeByName = function (name) {
  22310. var mesh = this.getMeshByName(name);
  22311. if (mesh) {
  22312. return mesh;
  22313. }
  22314. var light = this.getLightByName(name);
  22315. if (light) {
  22316. return light;
  22317. }
  22318. var camera = this.getCameraByName(name);
  22319. if (camera) {
  22320. return camera;
  22321. }
  22322. var bone = this.getBoneByName(name);
  22323. return bone;
  22324. };
  22325. Scene.prototype.getMeshByName = function (name) {
  22326. for (var index = 0; index < this.meshes.length; index++) {
  22327. if (this.meshes[index].name === name) {
  22328. return this.meshes[index];
  22329. }
  22330. }
  22331. return null;
  22332. };
  22333. Scene.prototype.getTransformNodeByName = function (name) {
  22334. for (var index = 0; index < this.transformNodes.length; index++) {
  22335. if (this.transformNodes[index].name === name) {
  22336. return this.transformNodes[index];
  22337. }
  22338. }
  22339. return null;
  22340. };
  22341. Scene.prototype.getSoundByName = function (name) {
  22342. var index;
  22343. if (BABYLON.AudioEngine) {
  22344. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22345. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22346. return this.mainSoundTrack.soundCollection[index];
  22347. }
  22348. }
  22349. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22350. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22351. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22352. return this.soundTracks[sdIndex].soundCollection[index];
  22353. }
  22354. }
  22355. }
  22356. }
  22357. return null;
  22358. };
  22359. Scene.prototype.getLastSkeletonByID = function (id) {
  22360. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22361. if (this.skeletons[index].id === id) {
  22362. return this.skeletons[index];
  22363. }
  22364. }
  22365. return null;
  22366. };
  22367. Scene.prototype.getSkeletonById = function (id) {
  22368. for (var index = 0; index < this.skeletons.length; index++) {
  22369. if (this.skeletons[index].id === id) {
  22370. return this.skeletons[index];
  22371. }
  22372. }
  22373. return null;
  22374. };
  22375. Scene.prototype.getSkeletonByName = function (name) {
  22376. for (var index = 0; index < this.skeletons.length; index++) {
  22377. if (this.skeletons[index].name === name) {
  22378. return this.skeletons[index];
  22379. }
  22380. }
  22381. return null;
  22382. };
  22383. Scene.prototype.getMorphTargetManagerById = function (id) {
  22384. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22385. if (this.morphTargetManagers[index].uniqueId === id) {
  22386. return this.morphTargetManagers[index];
  22387. }
  22388. }
  22389. return null;
  22390. };
  22391. Scene.prototype.isActiveMesh = function (mesh) {
  22392. return (this._activeMeshes.indexOf(mesh) !== -1);
  22393. };
  22394. /**
  22395. * Return a the first highlight layer of the scene with a given name.
  22396. * @param name The name of the highlight layer to look for.
  22397. * @return The highlight layer if found otherwise null.
  22398. */
  22399. Scene.prototype.getHighlightLayerByName = function (name) {
  22400. for (var index = 0; index < this.highlightLayers.length; index++) {
  22401. if (this.highlightLayers[index].name === name) {
  22402. return this.highlightLayers[index];
  22403. }
  22404. }
  22405. return null;
  22406. };
  22407. Object.defineProperty(Scene.prototype, "uid", {
  22408. /**
  22409. * Return a unique id as a string which can serve as an identifier for the scene
  22410. */
  22411. get: function () {
  22412. if (!this._uid) {
  22413. this._uid = BABYLON.Tools.RandomId();
  22414. }
  22415. return this._uid;
  22416. },
  22417. enumerable: true,
  22418. configurable: true
  22419. });
  22420. /**
  22421. * Add an externaly attached data from its key.
  22422. * This method call will fail and return false, if such key already exists.
  22423. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22424. * @param key the unique key that identifies the data
  22425. * @param data the data object to associate to the key for this Engine instance
  22426. * @return true if no such key were already present and the data was added successfully, false otherwise
  22427. */
  22428. Scene.prototype.addExternalData = function (key, data) {
  22429. if (!this._externalData) {
  22430. this._externalData = new BABYLON.StringDictionary();
  22431. }
  22432. return this._externalData.add(key, data);
  22433. };
  22434. /**
  22435. * Get an externaly attached data from its key
  22436. * @param key the unique key that identifies the data
  22437. * @return the associated data, if present (can be null), or undefined if not present
  22438. */
  22439. Scene.prototype.getExternalData = function (key) {
  22440. if (!this._externalData) {
  22441. return null;
  22442. }
  22443. return this._externalData.get(key);
  22444. };
  22445. /**
  22446. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22447. * @param key the unique key that identifies the data
  22448. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22449. * @return the associated data, can be null if the factory returned null.
  22450. */
  22451. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22452. if (!this._externalData) {
  22453. this._externalData = new BABYLON.StringDictionary();
  22454. }
  22455. return this._externalData.getOrAddWithFactory(key, factory);
  22456. };
  22457. /**
  22458. * Remove an externaly attached data from the Engine instance
  22459. * @param key the unique key that identifies the data
  22460. * @return true if the data was successfully removed, false if it doesn't exist
  22461. */
  22462. Scene.prototype.removeExternalData = function (key) {
  22463. return this._externalData.remove(key);
  22464. };
  22465. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22466. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22467. if (mesh.showSubMeshesBoundingBox) {
  22468. var boundingInfo = subMesh.getBoundingInfo();
  22469. if (boundingInfo !== null && boundingInfo !== undefined) {
  22470. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22471. }
  22472. }
  22473. var material = subMesh.getMaterial();
  22474. if (material !== null && material !== undefined) {
  22475. // Render targets
  22476. if (material.getRenderTargetTextures !== undefined) {
  22477. if (this._processedMaterials.indexOf(material) === -1) {
  22478. this._processedMaterials.push(material);
  22479. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22480. }
  22481. }
  22482. // Dispatch
  22483. this._activeIndices.addCount(subMesh.indexCount, false);
  22484. this._renderingManager.dispatch(subMesh, mesh, material);
  22485. }
  22486. }
  22487. };
  22488. Scene.prototype._isInIntermediateRendering = function () {
  22489. return this._intermediateRendering;
  22490. };
  22491. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22492. this._activeMeshCandidateProvider = provider;
  22493. };
  22494. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22495. return this._activeMeshCandidateProvider;
  22496. };
  22497. /**
  22498. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22499. */
  22500. Scene.prototype.freezeActiveMeshes = function () {
  22501. this._evaluateActiveMeshes();
  22502. this._activeMeshesFrozen = true;
  22503. return this;
  22504. };
  22505. /**
  22506. * Use this function to restart evaluating active meshes on every frame
  22507. */
  22508. Scene.prototype.unfreezeActiveMeshes = function () {
  22509. this._activeMeshesFrozen = false;
  22510. return this;
  22511. };
  22512. Scene.prototype._evaluateActiveMeshes = function () {
  22513. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22514. return;
  22515. }
  22516. if (!this.activeCamera) {
  22517. return;
  22518. }
  22519. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22520. this.activeCamera._activeMeshes.reset();
  22521. this._activeMeshes.reset();
  22522. this._renderingManager.reset();
  22523. this._processedMaterials.reset();
  22524. this._activeParticleSystems.reset();
  22525. this._activeSkeletons.reset();
  22526. this._softwareSkinnedMeshes.reset();
  22527. if (this._boundingBoxRenderer) {
  22528. this._boundingBoxRenderer.reset();
  22529. }
  22530. // Meshes
  22531. var meshes;
  22532. var len;
  22533. var checkIsEnabled = true;
  22534. // Determine mesh candidates
  22535. if (this._activeMeshCandidateProvider !== undefined) {
  22536. // Use _activeMeshCandidateProvider
  22537. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22538. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22539. if (meshes !== undefined) {
  22540. len = meshes.length;
  22541. }
  22542. else {
  22543. len = 0;
  22544. }
  22545. }
  22546. else if (this._selectionOctree !== undefined) {
  22547. // Octree
  22548. var selection = this._selectionOctree.select(this._frustumPlanes);
  22549. meshes = selection.data;
  22550. len = selection.length;
  22551. }
  22552. else {
  22553. // Full scene traversal
  22554. len = this.meshes.length;
  22555. meshes = this.meshes;
  22556. }
  22557. // Check each mesh
  22558. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22559. mesh = meshes[meshIndex];
  22560. if (mesh.isBlocked) {
  22561. continue;
  22562. }
  22563. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22564. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22565. continue;
  22566. }
  22567. mesh.computeWorldMatrix();
  22568. // Intersections
  22569. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22570. this._meshesForIntersections.pushNoDuplicate(mesh);
  22571. }
  22572. // Switch to current LOD
  22573. meshLOD = mesh.getLOD(this.activeCamera);
  22574. if (meshLOD === undefined || meshLOD === null) {
  22575. continue;
  22576. }
  22577. mesh._preActivate();
  22578. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22579. this._activeMeshes.push(mesh);
  22580. this.activeCamera._activeMeshes.push(mesh);
  22581. mesh._activate(this._renderId);
  22582. if (meshLOD !== mesh) {
  22583. meshLOD._activate(this._renderId);
  22584. }
  22585. this._activeMesh(mesh, meshLOD);
  22586. }
  22587. }
  22588. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22589. // Particle systems
  22590. if (this.particlesEnabled) {
  22591. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22592. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22593. var particleSystem = this.particleSystems[particleIndex];
  22594. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22595. continue;
  22596. }
  22597. var emitter = particleSystem.emitter;
  22598. if (!emitter.position || emitter.isEnabled()) {
  22599. this._activeParticleSystems.push(particleSystem);
  22600. particleSystem.animate();
  22601. this._renderingManager.dispatchParticles(particleSystem);
  22602. }
  22603. }
  22604. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22605. }
  22606. };
  22607. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22608. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22609. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22610. mesh.skeleton.prepare();
  22611. }
  22612. if (!mesh.computeBonesUsingShaders) {
  22613. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22614. }
  22615. }
  22616. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22617. var boundingInfo = sourceMesh.getBoundingInfo();
  22618. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22619. }
  22620. if (mesh !== undefined && mesh !== null
  22621. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22622. // Submeshes Octrees
  22623. var len;
  22624. var subMeshes;
  22625. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22626. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22627. len = intersections.length;
  22628. subMeshes = intersections.data;
  22629. }
  22630. else {
  22631. subMeshes = mesh.subMeshes;
  22632. len = subMeshes.length;
  22633. }
  22634. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22635. subMesh = subMeshes[subIndex];
  22636. this._evaluateSubMesh(subMesh, mesh);
  22637. }
  22638. }
  22639. };
  22640. Scene.prototype.updateTransformMatrix = function (force) {
  22641. if (!this.activeCamera) {
  22642. return;
  22643. }
  22644. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22645. };
  22646. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22647. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22648. };
  22649. Scene.prototype._renderForCamera = function (camera) {
  22650. if (camera && camera._skipRendering) {
  22651. return;
  22652. }
  22653. var engine = this._engine;
  22654. this.activeCamera = camera;
  22655. if (!this.activeCamera)
  22656. throw new Error("Active camera not set");
  22657. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22658. // Viewport
  22659. engine.setViewport(this.activeCamera.viewport);
  22660. // Camera
  22661. this.resetCachedMaterial();
  22662. this._renderId++;
  22663. this.activeCamera.update();
  22664. this.updateTransformMatrix();
  22665. if (camera._alternateCamera) {
  22666. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22667. this._alternateRendering = true;
  22668. }
  22669. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22670. // Meshes
  22671. this._evaluateActiveMeshes();
  22672. // Software skinning
  22673. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22674. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22675. mesh.applySkeleton(mesh.skeleton);
  22676. }
  22677. // Render targets
  22678. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22679. var needsRestoreFrameBuffer = false;
  22680. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22681. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22682. }
  22683. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22684. this._intermediateRendering = true;
  22685. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22686. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22687. var renderTarget = this._renderTargets.data[renderIndex];
  22688. if (renderTarget._shouldRender()) {
  22689. this._renderId++;
  22690. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22691. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22692. }
  22693. }
  22694. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22695. this._intermediateRendering = false;
  22696. this._renderId++;
  22697. needsRestoreFrameBuffer = true; // Restore back buffer
  22698. }
  22699. // Render HighlightLayer Texture
  22700. var stencilState = this._engine.getStencilBuffer();
  22701. var renderhighlights = false;
  22702. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22703. this._intermediateRendering = true;
  22704. for (var i = 0; i < this.highlightLayers.length; i++) {
  22705. var highlightLayer = this.highlightLayers[i];
  22706. if (highlightLayer.shouldRender() &&
  22707. (!highlightLayer.camera ||
  22708. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22709. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22710. renderhighlights = true;
  22711. var renderTarget = highlightLayer._mainTexture;
  22712. if (renderTarget._shouldRender()) {
  22713. this._renderId++;
  22714. renderTarget.render(false, false);
  22715. needsRestoreFrameBuffer = true;
  22716. }
  22717. }
  22718. }
  22719. this._intermediateRendering = false;
  22720. this._renderId++;
  22721. }
  22722. if (needsRestoreFrameBuffer) {
  22723. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22724. }
  22725. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22726. // Prepare Frame
  22727. this.postProcessManager._prepareFrame();
  22728. // Backgrounds
  22729. var layerIndex;
  22730. var layer;
  22731. if (this.layers.length) {
  22732. engine.setDepthBuffer(false);
  22733. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22734. layer = this.layers[layerIndex];
  22735. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22736. layer.render();
  22737. }
  22738. }
  22739. engine.setDepthBuffer(true);
  22740. }
  22741. // Activate HighlightLayer stencil
  22742. if (renderhighlights) {
  22743. this._engine.setStencilBuffer(true);
  22744. }
  22745. // Render
  22746. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22747. this._renderingManager.render(null, null, true, true);
  22748. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22749. // Restore HighlightLayer stencil
  22750. if (renderhighlights) {
  22751. this._engine.setStencilBuffer(stencilState);
  22752. }
  22753. // Bounding boxes
  22754. if (this._boundingBoxRenderer) {
  22755. this._boundingBoxRenderer.render();
  22756. }
  22757. // Lens flares
  22758. if (this.lensFlaresEnabled) {
  22759. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22760. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22761. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22762. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22763. lensFlareSystem.render();
  22764. }
  22765. }
  22766. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22767. }
  22768. // Foregrounds
  22769. if (this.layers.length) {
  22770. engine.setDepthBuffer(false);
  22771. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22772. layer = this.layers[layerIndex];
  22773. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22774. layer.render();
  22775. }
  22776. }
  22777. engine.setDepthBuffer(true);
  22778. }
  22779. // Highlight Layer
  22780. if (renderhighlights) {
  22781. engine.setDepthBuffer(false);
  22782. for (var i = 0; i < this.highlightLayers.length; i++) {
  22783. if (this.highlightLayers[i].shouldRender()) {
  22784. this.highlightLayers[i].render();
  22785. }
  22786. }
  22787. engine.setDepthBuffer(true);
  22788. }
  22789. // Finalize frame
  22790. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22791. // Reset some special arrays
  22792. this._renderTargets.reset();
  22793. this._alternateRendering = false;
  22794. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22795. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22796. };
  22797. Scene.prototype._processSubCameras = function (camera) {
  22798. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22799. this._renderForCamera(camera);
  22800. return;
  22801. }
  22802. // Update camera
  22803. if (this.activeCamera) {
  22804. this.activeCamera.update();
  22805. }
  22806. // rig cameras
  22807. for (var index = 0; index < camera._rigCameras.length; index++) {
  22808. this._renderForCamera(camera._rigCameras[index]);
  22809. }
  22810. this.activeCamera = camera;
  22811. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22812. };
  22813. Scene.prototype._checkIntersections = function () {
  22814. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22815. var sourceMesh = this._meshesForIntersections.data[index];
  22816. if (!sourceMesh.actionManager) {
  22817. continue;
  22818. }
  22819. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22820. var action = sourceMesh.actionManager.actions[actionIndex];
  22821. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22822. var parameters = action.getTriggerParameter();
  22823. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22824. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22825. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22826. if (areIntersecting && currentIntersectionInProgress === -1) {
  22827. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22828. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22829. sourceMesh._intersectionsInProgress.push(otherMesh);
  22830. }
  22831. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22832. sourceMesh._intersectionsInProgress.push(otherMesh);
  22833. }
  22834. }
  22835. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22836. //They intersected, and now they don't.
  22837. //is this trigger an exit trigger? execute an event.
  22838. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22839. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22840. }
  22841. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22842. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22843. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22844. }
  22845. }
  22846. }
  22847. }
  22848. }
  22849. };
  22850. Scene.prototype.render = function () {
  22851. if (this.isDisposed) {
  22852. return;
  22853. }
  22854. this._activeParticles.fetchNewFrame();
  22855. this._totalVertices.fetchNewFrame();
  22856. this._activeIndices.fetchNewFrame();
  22857. this._activeBones.fetchNewFrame();
  22858. this._meshesForIntersections.reset();
  22859. this.resetCachedMaterial();
  22860. this.onBeforeAnimationsObservable.notifyObservers(this);
  22861. // Actions
  22862. if (this.actionManager) {
  22863. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22864. }
  22865. //Simplification Queue
  22866. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22867. this.simplificationQueue.executeNext();
  22868. }
  22869. if (this._engine.isDeterministicLockStep()) {
  22870. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22871. var defaultFPS = (60.0 / 1000.0);
  22872. var defaultFrameTime = 1000 / 60; // frame time in MS
  22873. if (this._physicsEngine) {
  22874. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22875. }
  22876. var stepsTaken = 0;
  22877. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22878. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22879. internalSteps = Math.min(internalSteps, maxSubSteps);
  22880. do {
  22881. this.onBeforeStepObservable.notifyObservers(this);
  22882. // Animations
  22883. this._animationRatio = defaultFrameTime * defaultFPS;
  22884. this._animate();
  22885. this.onAfterAnimationsObservable.notifyObservers(this);
  22886. // Physics
  22887. if (this._physicsEngine) {
  22888. this.onBeforePhysicsObservable.notifyObservers(this);
  22889. this._physicsEngine._step(defaultFrameTime / 1000);
  22890. this.onAfterPhysicsObservable.notifyObservers(this);
  22891. }
  22892. this.onAfterStepObservable.notifyObservers(this);
  22893. this._currentStepId++;
  22894. stepsTaken++;
  22895. deltaTime -= defaultFrameTime;
  22896. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22897. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22898. }
  22899. else {
  22900. // Animations
  22901. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22902. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22903. this._animate();
  22904. this.onAfterAnimationsObservable.notifyObservers(this);
  22905. // Physics
  22906. if (this._physicsEngine) {
  22907. this.onBeforePhysicsObservable.notifyObservers(this);
  22908. this._physicsEngine._step(deltaTime / 1000.0);
  22909. this.onAfterPhysicsObservable.notifyObservers(this);
  22910. }
  22911. }
  22912. // update gamepad manager
  22913. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22914. this._gamepadManager._checkGamepadsStatus();
  22915. }
  22916. // Before render
  22917. this.onBeforeRenderObservable.notifyObservers(this);
  22918. // Customs render targets
  22919. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22920. var engine = this.getEngine();
  22921. var currentActiveCamera = this.activeCamera;
  22922. if (this.renderTargetsEnabled) {
  22923. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22924. this._intermediateRendering = true;
  22925. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22926. var renderTarget = this.customRenderTargets[customIndex];
  22927. if (renderTarget._shouldRender()) {
  22928. this._renderId++;
  22929. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22930. if (!this.activeCamera)
  22931. throw new Error("Active camera not set");
  22932. // Viewport
  22933. engine.setViewport(this.activeCamera.viewport);
  22934. // Camera
  22935. this.updateTransformMatrix();
  22936. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22937. }
  22938. }
  22939. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22940. this._intermediateRendering = false;
  22941. this._renderId++;
  22942. }
  22943. // Restore back buffer
  22944. if (this.customRenderTargets.length > 0) {
  22945. engine.restoreDefaultFramebuffer();
  22946. }
  22947. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22948. this.activeCamera = currentActiveCamera;
  22949. // Procedural textures
  22950. if (this.proceduralTexturesEnabled) {
  22951. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22952. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22953. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22954. if (proceduralTexture._shouldRender()) {
  22955. proceduralTexture.render();
  22956. }
  22957. }
  22958. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22959. }
  22960. // Clear
  22961. if (this.autoClearDepthAndStencil || this.autoClear) {
  22962. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22963. }
  22964. // Shadows
  22965. if (this.shadowsEnabled) {
  22966. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22967. var light = this.lights[lightIndex];
  22968. var shadowGenerator = light.getShadowGenerator();
  22969. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22970. var shadowMap = (shadowGenerator.getShadowMap());
  22971. if (this.textures.indexOf(shadowMap) !== -1) {
  22972. this._renderTargets.push(shadowMap);
  22973. }
  22974. }
  22975. }
  22976. }
  22977. // Depth renderer
  22978. if (this._depthRenderer) {
  22979. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22980. }
  22981. // Geometry renderer
  22982. if (this._geometryBufferRenderer) {
  22983. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22984. }
  22985. // RenderPipeline
  22986. if (this._postProcessRenderPipelineManager) {
  22987. this._postProcessRenderPipelineManager.update();
  22988. }
  22989. // Multi-cameras?
  22990. if (this.activeCameras.length > 0) {
  22991. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22992. if (cameraIndex > 0) {
  22993. this._engine.clear(null, false, true, true);
  22994. }
  22995. this._processSubCameras(this.activeCameras[cameraIndex]);
  22996. }
  22997. }
  22998. else {
  22999. if (!this.activeCamera) {
  23000. throw new Error("No camera defined");
  23001. }
  23002. this._processSubCameras(this.activeCamera);
  23003. }
  23004. // Intersection checks
  23005. this._checkIntersections();
  23006. // Update the audio listener attached to the camera
  23007. if (BABYLON.AudioEngine) {
  23008. this._updateAudioParameters();
  23009. }
  23010. // After render
  23011. if (this.afterRender) {
  23012. this.afterRender();
  23013. }
  23014. this.onAfterRenderObservable.notifyObservers(this);
  23015. // Cleaning
  23016. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23017. var data = this._toBeDisposed.data[index];
  23018. if (data) {
  23019. data.dispose();
  23020. }
  23021. this._toBeDisposed[index] = null;
  23022. }
  23023. this._toBeDisposed.reset();
  23024. if (this.dumpNextRenderTargets) {
  23025. this.dumpNextRenderTargets = false;
  23026. }
  23027. this._activeBones.addCount(0, true);
  23028. this._activeIndices.addCount(0, true);
  23029. this._activeParticles.addCount(0, true);
  23030. };
  23031. Scene.prototype._updateAudioParameters = function () {
  23032. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23033. return;
  23034. }
  23035. var listeningCamera;
  23036. var audioEngine = BABYLON.Engine.audioEngine;
  23037. if (this.activeCameras.length > 0) {
  23038. listeningCamera = this.activeCameras[0];
  23039. }
  23040. else {
  23041. listeningCamera = this.activeCamera;
  23042. }
  23043. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23044. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23045. // for VR cameras
  23046. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23047. listeningCamera = listeningCamera.rigCameras[0];
  23048. }
  23049. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23050. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23051. cameraDirection.normalize();
  23052. // To avoid some errors on GearVR
  23053. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23054. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23055. }
  23056. var i;
  23057. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23058. var sound = this.mainSoundTrack.soundCollection[i];
  23059. if (sound.useCustomAttenuation) {
  23060. sound.updateDistanceFromListener();
  23061. }
  23062. }
  23063. for (i = 0; i < this.soundTracks.length; i++) {
  23064. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23065. sound = this.soundTracks[i].soundCollection[j];
  23066. if (sound.useCustomAttenuation) {
  23067. sound.updateDistanceFromListener();
  23068. }
  23069. }
  23070. }
  23071. }
  23072. };
  23073. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23074. // Audio
  23075. get: function () {
  23076. return this._audioEnabled;
  23077. },
  23078. set: function (value) {
  23079. this._audioEnabled = value;
  23080. if (BABYLON.AudioEngine) {
  23081. if (this._audioEnabled) {
  23082. this._enableAudio();
  23083. }
  23084. else {
  23085. this._disableAudio();
  23086. }
  23087. }
  23088. },
  23089. enumerable: true,
  23090. configurable: true
  23091. });
  23092. Scene.prototype._disableAudio = function () {
  23093. var i;
  23094. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23095. this.mainSoundTrack.soundCollection[i].pause();
  23096. }
  23097. for (i = 0; i < this.soundTracks.length; i++) {
  23098. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23099. this.soundTracks[i].soundCollection[j].pause();
  23100. }
  23101. }
  23102. };
  23103. Scene.prototype._enableAudio = function () {
  23104. var i;
  23105. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23106. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23107. this.mainSoundTrack.soundCollection[i].play();
  23108. }
  23109. }
  23110. for (i = 0; i < this.soundTracks.length; i++) {
  23111. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23112. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23113. this.soundTracks[i].soundCollection[j].play();
  23114. }
  23115. }
  23116. }
  23117. };
  23118. Object.defineProperty(Scene.prototype, "headphone", {
  23119. get: function () {
  23120. return this._headphone;
  23121. },
  23122. set: function (value) {
  23123. this._headphone = value;
  23124. if (BABYLON.AudioEngine) {
  23125. if (this._headphone) {
  23126. this._switchAudioModeForHeadphones();
  23127. }
  23128. else {
  23129. this._switchAudioModeForNormalSpeakers();
  23130. }
  23131. }
  23132. },
  23133. enumerable: true,
  23134. configurable: true
  23135. });
  23136. Scene.prototype._switchAudioModeForHeadphones = function () {
  23137. this.mainSoundTrack.switchPanningModelToHRTF();
  23138. for (var i = 0; i < this.soundTracks.length; i++) {
  23139. this.soundTracks[i].switchPanningModelToHRTF();
  23140. }
  23141. };
  23142. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23143. this.mainSoundTrack.switchPanningModelToEqualPower();
  23144. for (var i = 0; i < this.soundTracks.length; i++) {
  23145. this.soundTracks[i].switchPanningModelToEqualPower();
  23146. }
  23147. };
  23148. Scene.prototype.enableDepthRenderer = function () {
  23149. if (this._depthRenderer) {
  23150. return this._depthRenderer;
  23151. }
  23152. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23153. return this._depthRenderer;
  23154. };
  23155. Scene.prototype.disableDepthRenderer = function () {
  23156. if (!this._depthRenderer) {
  23157. return;
  23158. }
  23159. this._depthRenderer.dispose();
  23160. this._depthRenderer = null;
  23161. };
  23162. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23163. if (ratio === void 0) { ratio = 1; }
  23164. if (this._geometryBufferRenderer) {
  23165. return this._geometryBufferRenderer;
  23166. }
  23167. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23168. if (!this._geometryBufferRenderer.isSupported) {
  23169. this._geometryBufferRenderer = null;
  23170. }
  23171. return this._geometryBufferRenderer;
  23172. };
  23173. Scene.prototype.disableGeometryBufferRenderer = function () {
  23174. if (!this._geometryBufferRenderer) {
  23175. return;
  23176. }
  23177. this._geometryBufferRenderer.dispose();
  23178. this._geometryBufferRenderer = null;
  23179. };
  23180. Scene.prototype.freezeMaterials = function () {
  23181. for (var i = 0; i < this.materials.length; i++) {
  23182. this.materials[i].freeze();
  23183. }
  23184. };
  23185. Scene.prototype.unfreezeMaterials = function () {
  23186. for (var i = 0; i < this.materials.length; i++) {
  23187. this.materials[i].unfreeze();
  23188. }
  23189. };
  23190. Scene.prototype.dispose = function () {
  23191. this.beforeRender = null;
  23192. this.afterRender = null;
  23193. this.skeletons = [];
  23194. this.morphTargetManagers = [];
  23195. this.importedMeshesFiles = new Array();
  23196. this.stopAllAnimations();
  23197. this.resetCachedMaterial();
  23198. if (this._depthRenderer) {
  23199. this._depthRenderer.dispose();
  23200. }
  23201. if (this._gamepadManager) {
  23202. this._gamepadManager.dispose();
  23203. this._gamepadManager = null;
  23204. }
  23205. // Smart arrays
  23206. if (this.activeCamera) {
  23207. this.activeCamera._activeMeshes.dispose();
  23208. this.activeCamera = null;
  23209. }
  23210. this._activeMeshes.dispose();
  23211. this._renderingManager.dispose();
  23212. this._processedMaterials.dispose();
  23213. this._activeParticleSystems.dispose();
  23214. this._activeSkeletons.dispose();
  23215. this._softwareSkinnedMeshes.dispose();
  23216. this._renderTargets.dispose();
  23217. if (this._boundingBoxRenderer) {
  23218. this._boundingBoxRenderer.dispose();
  23219. }
  23220. this._meshesForIntersections.dispose();
  23221. this._toBeDisposed.dispose();
  23222. // Abort active requests
  23223. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23224. var request = _a[_i];
  23225. request.abort();
  23226. }
  23227. // Debug layer
  23228. if (this._debugLayer) {
  23229. this._debugLayer.hide();
  23230. }
  23231. // Events
  23232. this.onDisposeObservable.notifyObservers(this);
  23233. this.onDisposeObservable.clear();
  23234. this.onBeforeRenderObservable.clear();
  23235. this.onAfterRenderObservable.clear();
  23236. this.OnBeforeRenderTargetsRenderObservable.clear();
  23237. this.OnAfterRenderTargetsRenderObservable.clear();
  23238. this.onAfterStepObservable.clear();
  23239. this.onBeforeStepObservable.clear();
  23240. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23241. this.onAfterActiveMeshesEvaluationObservable.clear();
  23242. this.onBeforeParticlesRenderingObservable.clear();
  23243. this.onAfterParticlesRenderingObservable.clear();
  23244. this.onBeforeSpritesRenderingObservable.clear();
  23245. this.onAfterSpritesRenderingObservable.clear();
  23246. this.onBeforeDrawPhaseObservable.clear();
  23247. this.onAfterDrawPhaseObservable.clear();
  23248. this.onBeforePhysicsObservable.clear();
  23249. this.onAfterPhysicsObservable.clear();
  23250. this.onBeforeAnimationsObservable.clear();
  23251. this.onAfterAnimationsObservable.clear();
  23252. this.onDataLoadedObservable.clear();
  23253. this.detachControl();
  23254. // Release sounds & sounds tracks
  23255. if (BABYLON.AudioEngine) {
  23256. this.disposeSounds();
  23257. }
  23258. // VR Helper
  23259. if (this.VRHelper) {
  23260. this.VRHelper.dispose();
  23261. }
  23262. // Detach cameras
  23263. var canvas = this._engine.getRenderingCanvas();
  23264. if (canvas) {
  23265. var index;
  23266. for (index = 0; index < this.cameras.length; index++) {
  23267. this.cameras[index].detachControl(canvas);
  23268. }
  23269. }
  23270. // Release animation groups
  23271. while (this.animationGroups.length) {
  23272. this.animationGroups[0].dispose();
  23273. }
  23274. // Release lights
  23275. while (this.lights.length) {
  23276. this.lights[0].dispose();
  23277. }
  23278. // Release meshes
  23279. while (this.meshes.length) {
  23280. this.meshes[0].dispose(true);
  23281. }
  23282. while (this.transformNodes.length) {
  23283. this.removeTransformNode(this.transformNodes[0]);
  23284. }
  23285. // Release cameras
  23286. while (this.cameras.length) {
  23287. this.cameras[0].dispose();
  23288. }
  23289. // Release materials
  23290. if (this.defaultMaterial) {
  23291. this.defaultMaterial.dispose();
  23292. }
  23293. while (this.multiMaterials.length) {
  23294. this.multiMaterials[0].dispose();
  23295. }
  23296. while (this.materials.length) {
  23297. this.materials[0].dispose();
  23298. }
  23299. // Release particles
  23300. while (this.particleSystems.length) {
  23301. this.particleSystems[0].dispose();
  23302. }
  23303. // Release sprites
  23304. while (this.spriteManagers.length) {
  23305. this.spriteManagers[0].dispose();
  23306. }
  23307. // Release postProcesses
  23308. while (this.postProcesses.length) {
  23309. this.postProcesses[0].dispose();
  23310. }
  23311. // Release layers
  23312. while (this.layers.length) {
  23313. this.layers[0].dispose();
  23314. }
  23315. while (this.highlightLayers.length) {
  23316. this.highlightLayers[0].dispose();
  23317. }
  23318. // Release textures
  23319. while (this.textures.length) {
  23320. this.textures[0].dispose();
  23321. }
  23322. // Release UBO
  23323. this._sceneUbo.dispose();
  23324. if (this._alternateSceneUbo) {
  23325. this._alternateSceneUbo.dispose();
  23326. }
  23327. // Post-processes
  23328. this.postProcessManager.dispose();
  23329. if (this._postProcessRenderPipelineManager) {
  23330. this._postProcessRenderPipelineManager.dispose();
  23331. }
  23332. // Physics
  23333. if (this._physicsEngine) {
  23334. this.disablePhysicsEngine();
  23335. }
  23336. // Remove from engine
  23337. index = this._engine.scenes.indexOf(this);
  23338. if (index > -1) {
  23339. this._engine.scenes.splice(index, 1);
  23340. }
  23341. this._engine.wipeCaches(true);
  23342. this._isDisposed = true;
  23343. };
  23344. Object.defineProperty(Scene.prototype, "isDisposed", {
  23345. get: function () {
  23346. return this._isDisposed;
  23347. },
  23348. enumerable: true,
  23349. configurable: true
  23350. });
  23351. // Release sounds & sounds tracks
  23352. Scene.prototype.disposeSounds = function () {
  23353. if (!this._mainSoundTrack) {
  23354. return;
  23355. }
  23356. this.mainSoundTrack.dispose();
  23357. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23358. this.soundTracks[scIndex].dispose();
  23359. }
  23360. };
  23361. // Octrees
  23362. Scene.prototype.getWorldExtends = function () {
  23363. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23364. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23365. for (var index = 0; index < this.meshes.length; index++) {
  23366. var mesh = this.meshes[index];
  23367. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23368. continue;
  23369. }
  23370. mesh.computeWorldMatrix(true);
  23371. var boundingInfo = mesh.getBoundingInfo();
  23372. var minBox = boundingInfo.boundingBox.minimumWorld;
  23373. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23374. BABYLON.Tools.CheckExtends(minBox, min, max);
  23375. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23376. }
  23377. return {
  23378. min: min,
  23379. max: max
  23380. };
  23381. };
  23382. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23383. if (maxCapacity === void 0) { maxCapacity = 64; }
  23384. if (maxDepth === void 0) { maxDepth = 2; }
  23385. if (!this._selectionOctree) {
  23386. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23387. }
  23388. var worldExtends = this.getWorldExtends();
  23389. // Update octree
  23390. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23391. return this._selectionOctree;
  23392. };
  23393. // Picking
  23394. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23395. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23396. var result = BABYLON.Ray.Zero();
  23397. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23398. return result;
  23399. };
  23400. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23401. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23402. var engine = this._engine;
  23403. if (!camera) {
  23404. if (!this.activeCamera)
  23405. throw new Error("Active camera not set");
  23406. camera = this.activeCamera;
  23407. }
  23408. var cameraViewport = camera.viewport;
  23409. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23410. // Moving coordinates to local viewport world
  23411. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23412. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23413. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23414. return this;
  23415. };
  23416. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23417. var result = BABYLON.Ray.Zero();
  23418. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23419. return result;
  23420. };
  23421. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23422. if (!BABYLON.PickingInfo) {
  23423. return this;
  23424. }
  23425. var engine = this._engine;
  23426. if (!camera) {
  23427. if (!this.activeCamera)
  23428. throw new Error("Active camera not set");
  23429. camera = this.activeCamera;
  23430. }
  23431. var cameraViewport = camera.viewport;
  23432. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23433. var identity = BABYLON.Matrix.Identity();
  23434. // Moving coordinates to local viewport world
  23435. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23436. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23437. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23438. return this;
  23439. };
  23440. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23441. if (!BABYLON.PickingInfo) {
  23442. return null;
  23443. }
  23444. var pickingInfo = null;
  23445. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23446. var mesh = this.meshes[meshIndex];
  23447. if (predicate) {
  23448. if (!predicate(mesh)) {
  23449. continue;
  23450. }
  23451. }
  23452. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23453. continue;
  23454. }
  23455. var world = mesh.getWorldMatrix();
  23456. var ray = rayFunction(world);
  23457. var result = mesh.intersects(ray, fastCheck);
  23458. if (!result || !result.hit)
  23459. continue;
  23460. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23461. continue;
  23462. pickingInfo = result;
  23463. if (fastCheck) {
  23464. break;
  23465. }
  23466. }
  23467. return pickingInfo || new BABYLON.PickingInfo();
  23468. };
  23469. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23470. if (!BABYLON.PickingInfo) {
  23471. return null;
  23472. }
  23473. var pickingInfos = new Array();
  23474. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23475. var mesh = this.meshes[meshIndex];
  23476. if (predicate) {
  23477. if (!predicate(mesh)) {
  23478. continue;
  23479. }
  23480. }
  23481. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23482. continue;
  23483. }
  23484. var world = mesh.getWorldMatrix();
  23485. var ray = rayFunction(world);
  23486. var result = mesh.intersects(ray, false);
  23487. if (!result || !result.hit)
  23488. continue;
  23489. pickingInfos.push(result);
  23490. }
  23491. return pickingInfos;
  23492. };
  23493. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23494. if (!BABYLON.PickingInfo) {
  23495. return null;
  23496. }
  23497. var pickingInfo = null;
  23498. if (!camera) {
  23499. if (!this.activeCamera) {
  23500. return null;
  23501. }
  23502. camera = this.activeCamera;
  23503. }
  23504. if (this.spriteManagers.length > 0) {
  23505. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23506. var spriteManager = this.spriteManagers[spriteIndex];
  23507. if (!spriteManager.isPickable) {
  23508. continue;
  23509. }
  23510. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23511. if (!result || !result.hit)
  23512. continue;
  23513. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23514. continue;
  23515. pickingInfo = result;
  23516. if (fastCheck) {
  23517. break;
  23518. }
  23519. }
  23520. }
  23521. return pickingInfo || new BABYLON.PickingInfo();
  23522. };
  23523. /** Launch a ray to try to pick a mesh in the scene
  23524. * @param x position on screen
  23525. * @param y position on screen
  23526. * @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
  23527. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23528. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23529. */
  23530. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23531. var _this = this;
  23532. if (!BABYLON.PickingInfo) {
  23533. return null;
  23534. }
  23535. return this._internalPick(function (world) {
  23536. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23537. return _this._tempPickingRay;
  23538. }, predicate, fastCheck);
  23539. };
  23540. /** Launch a ray to try to pick a sprite in the scene
  23541. * @param x position on screen
  23542. * @param y position on screen
  23543. * @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
  23544. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23545. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23546. */
  23547. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23548. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23549. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23550. };
  23551. /** Use the given ray to pick a mesh in the scene
  23552. * @param ray The ray to use to pick meshes
  23553. * @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
  23554. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23555. */
  23556. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23557. var _this = this;
  23558. return this._internalPick(function (world) {
  23559. if (!_this._pickWithRayInverseMatrix) {
  23560. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23561. }
  23562. world.invertToRef(_this._pickWithRayInverseMatrix);
  23563. if (!_this._cachedRayForTransform) {
  23564. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23565. }
  23566. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23567. return _this._cachedRayForTransform;
  23568. }, predicate, fastCheck);
  23569. };
  23570. /**
  23571. * Launch a ray to try to pick a mesh in the scene
  23572. * @param x X position on screen
  23573. * @param y Y position on screen
  23574. * @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
  23575. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23576. */
  23577. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23578. var _this = this;
  23579. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23580. };
  23581. /**
  23582. * Launch a ray to try to pick a mesh in the scene
  23583. * @param ray Ray to use
  23584. * @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
  23585. */
  23586. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23587. var _this = this;
  23588. return this._internalMultiPick(function (world) {
  23589. if (!_this._pickWithRayInverseMatrix) {
  23590. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23591. }
  23592. world.invertToRef(_this._pickWithRayInverseMatrix);
  23593. if (!_this._cachedRayForTransform) {
  23594. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23595. }
  23596. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23597. return _this._cachedRayForTransform;
  23598. }, predicate);
  23599. };
  23600. Scene.prototype.setPointerOverMesh = function (mesh) {
  23601. if (this._pointerOverMesh === mesh) {
  23602. return;
  23603. }
  23604. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23605. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23606. }
  23607. this._pointerOverMesh = mesh;
  23608. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23609. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23610. }
  23611. };
  23612. Scene.prototype.getPointerOverMesh = function () {
  23613. return this._pointerOverMesh;
  23614. };
  23615. Scene.prototype.setPointerOverSprite = function (sprite) {
  23616. if (this._pointerOverSprite === sprite) {
  23617. return;
  23618. }
  23619. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23620. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23621. }
  23622. this._pointerOverSprite = sprite;
  23623. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23624. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23625. }
  23626. };
  23627. Scene.prototype.getPointerOverSprite = function () {
  23628. return this._pointerOverSprite;
  23629. };
  23630. // Physics
  23631. Scene.prototype.getPhysicsEngine = function () {
  23632. return this._physicsEngine;
  23633. };
  23634. /**
  23635. * Enables physics to the current scene
  23636. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23637. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23638. * @return {boolean} was the physics engine initialized
  23639. */
  23640. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23641. if (gravity === void 0) { gravity = null; }
  23642. if (this._physicsEngine) {
  23643. return true;
  23644. }
  23645. try {
  23646. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23647. return true;
  23648. }
  23649. catch (e) {
  23650. BABYLON.Tools.Error(e.message);
  23651. return false;
  23652. }
  23653. };
  23654. Scene.prototype.disablePhysicsEngine = function () {
  23655. if (!this._physicsEngine) {
  23656. return;
  23657. }
  23658. this._physicsEngine.dispose();
  23659. this._physicsEngine = null;
  23660. };
  23661. Scene.prototype.isPhysicsEnabled = function () {
  23662. return this._physicsEngine !== undefined;
  23663. };
  23664. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23665. var mesh = compound.parts[0].mesh;
  23666. if (mesh.physicsImpostor) {
  23667. mesh.physicsImpostor.dispose();
  23668. mesh.physicsImpostor = null;
  23669. }
  23670. };
  23671. // Misc.
  23672. Scene.prototype._rebuildGeometries = function () {
  23673. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23674. var geometry = _a[_i];
  23675. geometry._rebuild();
  23676. }
  23677. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23678. var mesh = _c[_b];
  23679. mesh._rebuild();
  23680. }
  23681. if (this.postProcessManager) {
  23682. this.postProcessManager._rebuild();
  23683. }
  23684. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23685. var layer = _e[_d];
  23686. layer._rebuild();
  23687. }
  23688. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23689. var highlightLayer = _g[_f];
  23690. highlightLayer._rebuild();
  23691. }
  23692. if (this._boundingBoxRenderer) {
  23693. this._boundingBoxRenderer._rebuild();
  23694. }
  23695. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23696. var system = _j[_h];
  23697. system.rebuild();
  23698. }
  23699. if (this._postProcessRenderPipelineManager) {
  23700. this._postProcessRenderPipelineManager._rebuild();
  23701. }
  23702. };
  23703. Scene.prototype._rebuildTextures = function () {
  23704. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23705. var texture = _a[_i];
  23706. texture._rebuild();
  23707. }
  23708. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23709. };
  23710. /**
  23711. * Creates a default light for the scene.
  23712. * @param replace Whether to replace the existing lights in the scene.
  23713. */
  23714. Scene.prototype.createDefaultLight = function (replace) {
  23715. if (replace === void 0) { replace = false; }
  23716. // Dispose existing light in replace mode.
  23717. if (replace) {
  23718. if (this.lights) {
  23719. for (var i = 0; i < this.lights.length; i++) {
  23720. this.lights[i].dispose();
  23721. }
  23722. }
  23723. }
  23724. // Light
  23725. if (this.lights.length === 0) {
  23726. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23727. }
  23728. };
  23729. /**
  23730. * Creates a default camera for the scene.
  23731. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  23732. * @param replace Whether to replace the existing active camera in the scene.
  23733. * @param attachCameraControls Whether to attach camera controls to the canvas.
  23734. */
  23735. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  23736. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23737. if (replace === void 0) { replace = false; }
  23738. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23739. // Dispose existing camera in replace mode.
  23740. if (replace) {
  23741. if (this.activeCamera) {
  23742. this.activeCamera.dispose();
  23743. this.activeCamera = null;
  23744. }
  23745. }
  23746. // Camera
  23747. if (!this.activeCamera) {
  23748. var worldExtends = this.getWorldExtends();
  23749. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23750. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23751. var camera;
  23752. var radius = worldSize.length() * 1.5;
  23753. if (createArcRotateCamera) {
  23754. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23755. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23756. arcRotateCamera.wheelPrecision = 100 / radius;
  23757. camera = arcRotateCamera;
  23758. }
  23759. else {
  23760. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23761. freeCamera.setTarget(worldCenter);
  23762. camera = freeCamera;
  23763. }
  23764. camera.minZ = radius * 0.01;
  23765. camera.maxZ = radius * 1000;
  23766. camera.speed = radius * 0.2;
  23767. this.activeCamera = camera;
  23768. var canvas = this.getEngine().getRenderingCanvas();
  23769. if (attachCameraControls && canvas) {
  23770. camera.attachControl(canvas);
  23771. }
  23772. }
  23773. };
  23774. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23775. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23776. if (replace === void 0) { replace = false; }
  23777. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23778. this.createDefaultLight(replace);
  23779. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  23780. };
  23781. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23782. if (pbr === void 0) { pbr = false; }
  23783. if (scale === void 0) { scale = 1000; }
  23784. if (blur === void 0) { blur = 0; }
  23785. if (environmentTexture) {
  23786. this.environmentTexture = environmentTexture;
  23787. }
  23788. if (!this.environmentTexture) {
  23789. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23790. return null;
  23791. }
  23792. // Skybox
  23793. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23794. if (pbr) {
  23795. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23796. hdrSkyboxMaterial.backFaceCulling = false;
  23797. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23798. if (hdrSkyboxMaterial.reflectionTexture) {
  23799. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23800. }
  23801. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23802. hdrSkyboxMaterial.disableLighting = true;
  23803. hdrSkyboxMaterial.twoSidedLighting = true;
  23804. hdrSkybox.infiniteDistance = true;
  23805. hdrSkybox.material = hdrSkyboxMaterial;
  23806. }
  23807. else {
  23808. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23809. skyboxMaterial.backFaceCulling = false;
  23810. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23811. if (skyboxMaterial.reflectionTexture) {
  23812. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23813. }
  23814. skyboxMaterial.disableLighting = true;
  23815. hdrSkybox.infiniteDistance = true;
  23816. hdrSkybox.material = skyboxMaterial;
  23817. }
  23818. return hdrSkybox;
  23819. };
  23820. Scene.prototype.createDefaultEnvironment = function (options) {
  23821. if (BABYLON.EnvironmentHelper) {
  23822. return new BABYLON.EnvironmentHelper(options, this);
  23823. }
  23824. return null;
  23825. };
  23826. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23827. if (webVROptions === void 0) { webVROptions = {}; }
  23828. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23829. };
  23830. // Tags
  23831. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23832. if (tagsQuery === undefined) {
  23833. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23834. return list;
  23835. }
  23836. var listByTags = [];
  23837. forEach = forEach || (function (item) { return; });
  23838. for (var i in list) {
  23839. var item = list[i];
  23840. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23841. listByTags.push(item);
  23842. forEach(item);
  23843. }
  23844. }
  23845. return listByTags;
  23846. };
  23847. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23848. return this._getByTags(this.meshes, tagsQuery, forEach);
  23849. };
  23850. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23851. return this._getByTags(this.cameras, tagsQuery, forEach);
  23852. };
  23853. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23854. return this._getByTags(this.lights, tagsQuery, forEach);
  23855. };
  23856. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23857. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23858. };
  23859. /**
  23860. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23861. * This allowed control for front to back rendering or reversly depending of the special needs.
  23862. *
  23863. * @param renderingGroupId The rendering group id corresponding to its index
  23864. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23865. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23866. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23867. */
  23868. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23869. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23870. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23871. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23872. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23873. };
  23874. /**
  23875. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23876. *
  23877. * @param renderingGroupId The rendering group id corresponding to its index
  23878. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23879. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23880. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23881. */
  23882. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23883. if (depth === void 0) { depth = true; }
  23884. if (stencil === void 0) { stencil = true; }
  23885. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23886. };
  23887. /**
  23888. * Will flag all materials as dirty to trigger new shader compilation
  23889. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23890. */
  23891. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23892. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23893. var material = _a[_i];
  23894. if (predicate && !predicate(material)) {
  23895. continue;
  23896. }
  23897. material.markAsDirty(flag);
  23898. }
  23899. };
  23900. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23901. var _this = this;
  23902. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23903. this._activeRequests.push(request);
  23904. request.onCompleteObservable.add(function (request) {
  23905. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23906. });
  23907. return request;
  23908. };
  23909. /** @ignore */
  23910. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23911. var _this = this;
  23912. return new Promise(function (resolve, reject) {
  23913. _this._loadFile(url, function (data) {
  23914. resolve(data);
  23915. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23916. reject(exception);
  23917. });
  23918. });
  23919. };
  23920. // Statics
  23921. Scene._FOGMODE_NONE = 0;
  23922. Scene._FOGMODE_EXP = 1;
  23923. Scene._FOGMODE_EXP2 = 2;
  23924. Scene._FOGMODE_LINEAR = 3;
  23925. Scene._uniqueIdCounter = 0;
  23926. Scene.MinDeltaTime = 1.0;
  23927. Scene.MaxDeltaTime = 1000.0;
  23928. /** The distance in pixel that you have to move to prevent some events */
  23929. Scene.DragMovementThreshold = 10; // in pixels
  23930. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23931. Scene.LongPressDelay = 500; // in milliseconds
  23932. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23933. Scene.DoubleClickDelay = 300; // in milliseconds
  23934. /** If you need to check double click without raising a single click at first click, enable this flag */
  23935. Scene.ExclusiveDoubleClickMode = false;
  23936. return Scene;
  23937. }());
  23938. BABYLON.Scene = Scene;
  23939. })(BABYLON || (BABYLON = {}));
  23940. //# sourceMappingURL=babylon.scene.js.map
  23941. var BABYLON;
  23942. (function (BABYLON) {
  23943. /**
  23944. * Set of assets to keep when moving a scene into an asset container.
  23945. */
  23946. var KeepAssets = /** @class */ (function () {
  23947. function KeepAssets() {
  23948. /**
  23949. * Cameras to keep.
  23950. */
  23951. this.cameras = new Array();
  23952. /**
  23953. * Lights to keep.
  23954. */
  23955. this.lights = new Array();
  23956. /**
  23957. * Meshes to keep.
  23958. */
  23959. this.meshes = new Array();
  23960. /**
  23961. * Skeletons to keep.
  23962. */
  23963. this.skeletons = new Array();
  23964. /**
  23965. * ParticleSystems to keep.
  23966. */
  23967. this.particleSystems = new Array();
  23968. /**
  23969. * Animations to keep.
  23970. */
  23971. this.animations = new Array();
  23972. /**
  23973. * MultiMaterials to keep.
  23974. */
  23975. this.multiMaterials = new Array();
  23976. /**
  23977. * Materials to keep.
  23978. */
  23979. this.materials = new Array();
  23980. /**
  23981. * MorphTargetManagers to keep.
  23982. */
  23983. this.morphTargetManagers = new Array();
  23984. /**
  23985. * Geometries to keep.
  23986. */
  23987. this.geometries = new Array();
  23988. /**
  23989. * TransformNodes to keep.
  23990. */
  23991. this.transformNodes = new Array();
  23992. /**
  23993. * LensFlareSystems to keep.
  23994. */
  23995. this.lensFlareSystems = new Array();
  23996. /**
  23997. * ShadowGenerators to keep.
  23998. */
  23999. this.shadowGenerators = new Array();
  24000. /**
  24001. * ActionManagers to keep.
  24002. */
  24003. this.actionManagers = new Array();
  24004. /**
  24005. * Sounds to keep.
  24006. */
  24007. this.sounds = new Array();
  24008. }
  24009. return KeepAssets;
  24010. }());
  24011. BABYLON.KeepAssets = KeepAssets;
  24012. /**
  24013. * Container with a set of assets that can be added or removed from a scene.
  24014. */
  24015. var AssetContainer = /** @class */ (function () {
  24016. /**
  24017. * Instantiates an AssetContainer.
  24018. * @param scene The scene the AssetContainer belongs to.
  24019. */
  24020. function AssetContainer(scene) {
  24021. // Objects
  24022. /**
  24023. * Cameras populated in the container.
  24024. */
  24025. this.cameras = new Array();
  24026. /**
  24027. * Lights populated in the container.
  24028. */
  24029. this.lights = new Array();
  24030. /**
  24031. * Meshes populated in the container.
  24032. */
  24033. this.meshes = new Array();
  24034. /**
  24035. * Skeletons populated in the container.
  24036. */
  24037. this.skeletons = new Array();
  24038. /**
  24039. * ParticleSystems populated in the container.
  24040. */
  24041. this.particleSystems = new Array();
  24042. /**
  24043. * Animations populated in the container.
  24044. */
  24045. this.animations = new Array();
  24046. /**
  24047. * MultiMaterials populated in the container.
  24048. */
  24049. this.multiMaterials = new Array();
  24050. /**
  24051. * Materials populated in the container.
  24052. */
  24053. this.materials = new Array();
  24054. /**
  24055. * MorphTargetManagers populated in the container.
  24056. */
  24057. this.morphTargetManagers = new Array();
  24058. /**
  24059. * Geometries populated in the container.
  24060. */
  24061. this.geometries = new Array();
  24062. /**
  24063. * TransformNodes populated in the container.
  24064. */
  24065. this.transformNodes = new Array();
  24066. /**
  24067. * LensFlareSystems populated in the container.
  24068. */
  24069. this.lensFlareSystems = new Array();
  24070. /**
  24071. * ShadowGenerators populated in the container.
  24072. */
  24073. this.shadowGenerators = new Array();
  24074. /**
  24075. * ActionManagers populated in the container.
  24076. */
  24077. this.actionManagers = new Array();
  24078. /**
  24079. * Sounds populated in the container.
  24080. */
  24081. this.sounds = new Array();
  24082. this.scene = scene;
  24083. }
  24084. /**
  24085. * Adds all the assets from the container to the scene.
  24086. */
  24087. AssetContainer.prototype.addAllToScene = function () {
  24088. var _this = this;
  24089. this.cameras.forEach(function (o) {
  24090. _this.scene.addCamera(o);
  24091. });
  24092. this.lights.forEach(function (o) {
  24093. _this.scene.addLight(o);
  24094. });
  24095. this.meshes.forEach(function (o) {
  24096. _this.scene.addMesh(o);
  24097. });
  24098. this.skeletons.forEach(function (o) {
  24099. _this.scene.addSkeleton(o);
  24100. });
  24101. this.particleSystems.forEach(function (o) {
  24102. _this.scene.addParticleSystem(o);
  24103. });
  24104. this.animations.forEach(function (o) {
  24105. _this.scene.addAnimation(o);
  24106. });
  24107. this.multiMaterials.forEach(function (o) {
  24108. _this.scene.addMultiMaterial(o);
  24109. });
  24110. this.materials.forEach(function (o) {
  24111. _this.scene.addMaterial(o);
  24112. });
  24113. this.morphTargetManagers.forEach(function (o) {
  24114. _this.scene.addMorphTargetManager(o);
  24115. });
  24116. this.geometries.forEach(function (o) {
  24117. _this.scene.addGeometry(o);
  24118. });
  24119. this.transformNodes.forEach(function (o) {
  24120. _this.scene.addTransformNode(o);
  24121. });
  24122. this.lensFlareSystems.forEach(function (o) {
  24123. _this.scene.addLensFlareSystem(o);
  24124. });
  24125. this.actionManagers.forEach(function (o) {
  24126. _this.scene.addActionManager(o);
  24127. });
  24128. this.sounds.forEach(function (o) {
  24129. o.play();
  24130. o.autoplay = true;
  24131. _this.scene.mainSoundTrack.AddSound(o);
  24132. });
  24133. };
  24134. /**
  24135. * Removes all the assets in the container from the scene
  24136. */
  24137. AssetContainer.prototype.removeAllFromScene = function () {
  24138. var _this = this;
  24139. this.cameras.forEach(function (o) {
  24140. _this.scene.removeCamera(o);
  24141. });
  24142. this.lights.forEach(function (o) {
  24143. _this.scene.removeLight(o);
  24144. });
  24145. this.meshes.forEach(function (o) {
  24146. _this.scene.removeMesh(o);
  24147. });
  24148. this.skeletons.forEach(function (o) {
  24149. _this.scene.removeSkeleton(o);
  24150. });
  24151. this.particleSystems.forEach(function (o) {
  24152. _this.scene.removeParticleSystem(o);
  24153. });
  24154. this.animations.forEach(function (o) {
  24155. _this.scene.removeAnimation(o);
  24156. });
  24157. this.multiMaterials.forEach(function (o) {
  24158. _this.scene.removeMultiMaterial(o);
  24159. });
  24160. this.materials.forEach(function (o) {
  24161. _this.scene.removeMaterial(o);
  24162. });
  24163. this.morphTargetManagers.forEach(function (o) {
  24164. _this.scene.removeMorphTargetManager(o);
  24165. });
  24166. this.geometries.forEach(function (o) {
  24167. _this.scene.removeGeometry(o);
  24168. });
  24169. this.transformNodes.forEach(function (o) {
  24170. _this.scene.removeTransformNode(o);
  24171. });
  24172. this.lensFlareSystems.forEach(function (o) {
  24173. _this.scene.removeLensFlareSystem(o);
  24174. });
  24175. this.actionManagers.forEach(function (o) {
  24176. _this.scene.removeActionManager(o);
  24177. });
  24178. this.sounds.forEach(function (o) {
  24179. o.stop();
  24180. o.autoplay = false;
  24181. _this.scene.mainSoundTrack.RemoveSound(o);
  24182. });
  24183. };
  24184. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24185. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24186. var asset = sourceAssets_1[_i];
  24187. var move = true;
  24188. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24189. var keepAsset = keepAssets_1[_a];
  24190. if (asset === keepAsset) {
  24191. move = false;
  24192. break;
  24193. }
  24194. }
  24195. if (move) {
  24196. targetAssets.push(asset);
  24197. }
  24198. }
  24199. };
  24200. /**
  24201. * Removes all the assets contained in the scene and adds them to the container.
  24202. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24203. */
  24204. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24205. if (keepAssets === undefined) {
  24206. keepAssets = new KeepAssets();
  24207. }
  24208. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24209. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24210. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24211. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24212. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24213. Array.prototype.push.apply(this.animations, this.scene.animations);
  24214. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24215. Array.prototype.push.apply(this.lights, this.scene.lights);
  24216. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24217. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24218. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24219. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24220. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24221. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24222. this.removeAllFromScene();
  24223. };
  24224. return AssetContainer;
  24225. }());
  24226. BABYLON.AssetContainer = AssetContainer;
  24227. })(BABYLON || (BABYLON = {}));
  24228. //# sourceMappingURL=babylon.assetContainer.js.map
  24229. var BABYLON;
  24230. (function (BABYLON) {
  24231. var Buffer = /** @class */ (function () {
  24232. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24233. if (instanced === void 0) { instanced = false; }
  24234. if (engine instanceof BABYLON.Mesh) {
  24235. this._engine = engine.getScene().getEngine();
  24236. }
  24237. else {
  24238. this._engine = engine;
  24239. }
  24240. this._updatable = updatable;
  24241. this._data = data;
  24242. this._strideSize = stride;
  24243. if (!postponeInternalCreation) {
  24244. this.create();
  24245. }
  24246. this._instanced = instanced;
  24247. this._instanceDivisor = instanced ? 1 : 0;
  24248. }
  24249. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24250. // a lot of these parameters are ignored as they are overriden by the buffer
  24251. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24252. };
  24253. // Properties
  24254. Buffer.prototype.isUpdatable = function () {
  24255. return this._updatable;
  24256. };
  24257. Buffer.prototype.getData = function () {
  24258. return this._data;
  24259. };
  24260. Buffer.prototype.getBuffer = function () {
  24261. return this._buffer;
  24262. };
  24263. Buffer.prototype.getStrideSize = function () {
  24264. return this._strideSize;
  24265. };
  24266. Buffer.prototype.getIsInstanced = function () {
  24267. return this._instanced;
  24268. };
  24269. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24270. get: function () {
  24271. return this._instanceDivisor;
  24272. },
  24273. set: function (value) {
  24274. this._instanceDivisor = value;
  24275. if (value == 0) {
  24276. this._instanced = false;
  24277. }
  24278. else {
  24279. this._instanced = true;
  24280. }
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. // Methods
  24286. Buffer.prototype.create = function (data) {
  24287. if (data === void 0) { data = null; }
  24288. if (!data && this._buffer) {
  24289. return; // nothing to do
  24290. }
  24291. data = data || this._data;
  24292. if (!data) {
  24293. return;
  24294. }
  24295. if (!this._buffer) {
  24296. if (this._updatable) {
  24297. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24298. this._data = data;
  24299. }
  24300. else {
  24301. this._buffer = this._engine.createVertexBuffer(data);
  24302. }
  24303. }
  24304. else if (this._updatable) {
  24305. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24306. this._data = data;
  24307. }
  24308. };
  24309. Buffer.prototype._rebuild = function () {
  24310. this._buffer = null;
  24311. this.create(this._data);
  24312. };
  24313. Buffer.prototype.update = function (data) {
  24314. this.create(data);
  24315. };
  24316. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24317. if (!this._buffer) {
  24318. return;
  24319. }
  24320. if (this._updatable) {
  24321. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24322. this._data = null;
  24323. }
  24324. };
  24325. Buffer.prototype.dispose = function () {
  24326. if (!this._buffer) {
  24327. return;
  24328. }
  24329. if (this._engine._releaseBuffer(this._buffer)) {
  24330. this._buffer = null;
  24331. }
  24332. };
  24333. return Buffer;
  24334. }());
  24335. BABYLON.Buffer = Buffer;
  24336. })(BABYLON || (BABYLON = {}));
  24337. //# sourceMappingURL=babylon.buffer.js.map
  24338. var BABYLON;
  24339. (function (BABYLON) {
  24340. var VertexBuffer = /** @class */ (function () {
  24341. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24342. if (!stride) {
  24343. // Deduce stride from kind
  24344. switch (kind) {
  24345. case VertexBuffer.PositionKind:
  24346. stride = 3;
  24347. break;
  24348. case VertexBuffer.NormalKind:
  24349. stride = 3;
  24350. break;
  24351. case VertexBuffer.UVKind:
  24352. case VertexBuffer.UV2Kind:
  24353. case VertexBuffer.UV3Kind:
  24354. case VertexBuffer.UV4Kind:
  24355. case VertexBuffer.UV5Kind:
  24356. case VertexBuffer.UV6Kind:
  24357. stride = 2;
  24358. break;
  24359. case VertexBuffer.TangentKind:
  24360. case VertexBuffer.ColorKind:
  24361. stride = 4;
  24362. break;
  24363. case VertexBuffer.MatricesIndicesKind:
  24364. case VertexBuffer.MatricesIndicesExtraKind:
  24365. stride = 4;
  24366. break;
  24367. case VertexBuffer.MatricesWeightsKind:
  24368. case VertexBuffer.MatricesWeightsExtraKind:
  24369. default:
  24370. stride = 4;
  24371. break;
  24372. }
  24373. }
  24374. if (data instanceof BABYLON.Buffer) {
  24375. if (!stride) {
  24376. stride = data.getStrideSize();
  24377. }
  24378. this._buffer = data;
  24379. this._ownsBuffer = false;
  24380. }
  24381. else {
  24382. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24383. this._ownsBuffer = true;
  24384. }
  24385. this._stride = stride;
  24386. this._offset = offset ? offset : 0;
  24387. this._size = size ? size : stride;
  24388. this._kind = kind;
  24389. }
  24390. VertexBuffer.prototype._rebuild = function () {
  24391. if (!this._buffer) {
  24392. return;
  24393. }
  24394. this._buffer._rebuild();
  24395. };
  24396. /**
  24397. * Returns the kind of the VertexBuffer (string).
  24398. */
  24399. VertexBuffer.prototype.getKind = function () {
  24400. return this._kind;
  24401. };
  24402. // Properties
  24403. /**
  24404. * Boolean : is the VertexBuffer updatable ?
  24405. */
  24406. VertexBuffer.prototype.isUpdatable = function () {
  24407. return this._buffer.isUpdatable();
  24408. };
  24409. /**
  24410. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24411. */
  24412. VertexBuffer.prototype.getData = function () {
  24413. return this._buffer.getData();
  24414. };
  24415. /**
  24416. * Returns the WebGLBuffer associated to the VertexBuffer.
  24417. */
  24418. VertexBuffer.prototype.getBuffer = function () {
  24419. return this._buffer.getBuffer();
  24420. };
  24421. /**
  24422. * Returns the stride of the VertexBuffer (integer).
  24423. */
  24424. VertexBuffer.prototype.getStrideSize = function () {
  24425. return this._stride;
  24426. };
  24427. /**
  24428. * Returns the offset (integer).
  24429. */
  24430. VertexBuffer.prototype.getOffset = function () {
  24431. return this._offset;
  24432. };
  24433. /**
  24434. * Returns the VertexBuffer total size (integer).
  24435. */
  24436. VertexBuffer.prototype.getSize = function () {
  24437. return this._size;
  24438. };
  24439. /**
  24440. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24441. */
  24442. VertexBuffer.prototype.getIsInstanced = function () {
  24443. return this._buffer.getIsInstanced();
  24444. };
  24445. /**
  24446. * Returns the instancing divisor, zero for non-instanced (integer).
  24447. */
  24448. VertexBuffer.prototype.getInstanceDivisor = function () {
  24449. return this._buffer.instanceDivisor;
  24450. };
  24451. // Methods
  24452. /**
  24453. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24454. * Returns the created WebGLBuffer.
  24455. */
  24456. VertexBuffer.prototype.create = function (data) {
  24457. return this._buffer.create(data);
  24458. };
  24459. /**
  24460. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24461. * This function will create a new buffer if the current one is not updatable
  24462. * Returns the updated WebGLBuffer.
  24463. */
  24464. VertexBuffer.prototype.update = function (data) {
  24465. return this._buffer.update(data);
  24466. };
  24467. /**
  24468. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24469. * Returns the directly updated WebGLBuffer.
  24470. */
  24471. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24472. return this._buffer.updateDirectly(data, offset);
  24473. };
  24474. /**
  24475. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24476. */
  24477. VertexBuffer.prototype.dispose = function () {
  24478. if (this._ownsBuffer) {
  24479. this._buffer.dispose();
  24480. }
  24481. };
  24482. Object.defineProperty(VertexBuffer, "PositionKind", {
  24483. get: function () {
  24484. return VertexBuffer._PositionKind;
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. Object.defineProperty(VertexBuffer, "NormalKind", {
  24490. get: function () {
  24491. return VertexBuffer._NormalKind;
  24492. },
  24493. enumerable: true,
  24494. configurable: true
  24495. });
  24496. Object.defineProperty(VertexBuffer, "TangentKind", {
  24497. get: function () {
  24498. return VertexBuffer._TangentKind;
  24499. },
  24500. enumerable: true,
  24501. configurable: true
  24502. });
  24503. Object.defineProperty(VertexBuffer, "UVKind", {
  24504. get: function () {
  24505. return VertexBuffer._UVKind;
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24511. get: function () {
  24512. return VertexBuffer._UV2Kind;
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24518. get: function () {
  24519. return VertexBuffer._UV3Kind;
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24525. get: function () {
  24526. return VertexBuffer._UV4Kind;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24532. get: function () {
  24533. return VertexBuffer._UV5Kind;
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24539. get: function () {
  24540. return VertexBuffer._UV6Kind;
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(VertexBuffer, "ColorKind", {
  24546. get: function () {
  24547. return VertexBuffer._ColorKind;
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24553. get: function () {
  24554. return VertexBuffer._MatricesIndicesKind;
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24560. get: function () {
  24561. return VertexBuffer._MatricesWeightsKind;
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24567. get: function () {
  24568. return VertexBuffer._MatricesIndicesExtraKind;
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24574. get: function () {
  24575. return VertexBuffer._MatricesWeightsExtraKind;
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. // Enums
  24581. VertexBuffer._PositionKind = "position";
  24582. VertexBuffer._NormalKind = "normal";
  24583. VertexBuffer._TangentKind = "tangent";
  24584. VertexBuffer._UVKind = "uv";
  24585. VertexBuffer._UV2Kind = "uv2";
  24586. VertexBuffer._UV3Kind = "uv3";
  24587. VertexBuffer._UV4Kind = "uv4";
  24588. VertexBuffer._UV5Kind = "uv5";
  24589. VertexBuffer._UV6Kind = "uv6";
  24590. VertexBuffer._ColorKind = "color";
  24591. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24592. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24593. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24594. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24595. return VertexBuffer;
  24596. }());
  24597. BABYLON.VertexBuffer = VertexBuffer;
  24598. })(BABYLON || (BABYLON = {}));
  24599. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24600. var BABYLON;
  24601. (function (BABYLON) {
  24602. /**
  24603. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24604. */
  24605. var DummyInternalTextureTracker = /** @class */ (function () {
  24606. function DummyInternalTextureTracker() {
  24607. /**
  24608. * Gets or set the previous tracker in the list
  24609. */
  24610. this.previous = null;
  24611. /**
  24612. * Gets or set the next tracker in the list
  24613. */
  24614. this.next = null;
  24615. }
  24616. return DummyInternalTextureTracker;
  24617. }());
  24618. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24619. })(BABYLON || (BABYLON = {}));
  24620. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24621. var BABYLON;
  24622. (function (BABYLON) {
  24623. /**
  24624. * Class used to store data associated with WebGL texture data for the engine
  24625. * This class should not be used directly
  24626. */
  24627. var InternalTexture = /** @class */ (function () {
  24628. /**
  24629. * Creates a new InternalTexture
  24630. * @param engine defines the engine to use
  24631. * @param dataSource defines the type of data that will be used
  24632. */
  24633. function InternalTexture(engine, dataSource) {
  24634. /**
  24635. * Observable called when the texture is loaded
  24636. */
  24637. this.onLoadedObservable = new BABYLON.Observable();
  24638. /**
  24639. * Gets or set the previous tracker in the list
  24640. */
  24641. this.previous = null;
  24642. /**
  24643. * Gets or set the next tracker in the list
  24644. */
  24645. this.next = null;
  24646. // Private
  24647. /** @ignore */
  24648. this._initialSlot = -1;
  24649. /** @ignore */
  24650. this._designatedSlot = -1;
  24651. /** @ignore */
  24652. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24653. /** @ignore */
  24654. this._references = 1;
  24655. this._engine = engine;
  24656. this._dataSource = dataSource;
  24657. this._webGLTexture = engine._createTexture();
  24658. }
  24659. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24660. /**
  24661. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24662. */
  24663. get: function () {
  24664. return this._dataSource;
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. /**
  24670. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24671. */
  24672. InternalTexture.prototype.incrementReferences = function () {
  24673. this._references++;
  24674. };
  24675. /**
  24676. * Change the size of the texture (not the size of the content)
  24677. * @param width defines the new width
  24678. * @param height defines the new height
  24679. * @param depth defines the new depth (1 by default)
  24680. */
  24681. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24682. if (depth === void 0) { depth = 1; }
  24683. this.width = width;
  24684. this.height = height;
  24685. this.depth = depth;
  24686. this.baseWidth = width;
  24687. this.baseHeight = height;
  24688. this.baseDepth = depth;
  24689. this._size = width * height * depth;
  24690. };
  24691. /** @ignore */
  24692. InternalTexture.prototype._rebuild = function () {
  24693. var _this = this;
  24694. var proxy;
  24695. this.isReady = false;
  24696. this._cachedCoordinatesMode = null;
  24697. this._cachedWrapU = null;
  24698. this._cachedWrapV = null;
  24699. this._cachedAnisotropicFilteringLevel = null;
  24700. switch (this._dataSource) {
  24701. case InternalTexture.DATASOURCE_TEMP:
  24702. return;
  24703. case InternalTexture.DATASOURCE_URL:
  24704. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24705. _this.isReady = true;
  24706. }, null, this._buffer, undefined, this.format);
  24707. proxy._swapAndDie(this);
  24708. return;
  24709. case InternalTexture.DATASOURCE_RAW:
  24710. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24711. proxy._swapAndDie(this);
  24712. this.isReady = true;
  24713. return;
  24714. case InternalTexture.DATASOURCE_RAW3D:
  24715. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24716. proxy._swapAndDie(this);
  24717. this.isReady = true;
  24718. return;
  24719. case InternalTexture.DATASOURCE_DYNAMIC:
  24720. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24721. proxy._swapAndDie(this);
  24722. // The engine will make sure to update content so no need to flag it as isReady = true
  24723. return;
  24724. case InternalTexture.DATASOURCE_RENDERTARGET:
  24725. var options = new BABYLON.RenderTargetCreationOptions();
  24726. options.generateDepthBuffer = this._generateDepthBuffer;
  24727. options.generateMipMaps = this.generateMipMaps;
  24728. options.generateStencilBuffer = this._generateStencilBuffer;
  24729. options.samplingMode = this.samplingMode;
  24730. options.type = this.type;
  24731. if (this.isCube) {
  24732. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24733. }
  24734. else {
  24735. var size = {
  24736. width: this.width,
  24737. height: this.height
  24738. };
  24739. proxy = this._engine.createRenderTargetTexture(size, options);
  24740. }
  24741. proxy._swapAndDie(this);
  24742. this.isReady = true;
  24743. return;
  24744. case InternalTexture.DATASOURCE_CUBE:
  24745. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24746. _this.isReady = true;
  24747. }, null, this.format, this._extension);
  24748. proxy._swapAndDie(this);
  24749. return;
  24750. case InternalTexture.DATASOURCE_CUBERAW:
  24751. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24752. proxy._swapAndDie(this);
  24753. this.isReady = true;
  24754. return;
  24755. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24756. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24757. if (proxy) {
  24758. proxy._swapAndDie(_this);
  24759. }
  24760. _this.isReady = true;
  24761. }, null, this.format, this._extension);
  24762. return;
  24763. }
  24764. };
  24765. InternalTexture.prototype._swapAndDie = function (target) {
  24766. target._webGLTexture = this._webGLTexture;
  24767. if (this._framebuffer) {
  24768. target._framebuffer = this._framebuffer;
  24769. }
  24770. if (this._depthStencilBuffer) {
  24771. target._depthStencilBuffer = this._depthStencilBuffer;
  24772. }
  24773. if (this._lodTextureHigh) {
  24774. if (target._lodTextureHigh) {
  24775. target._lodTextureHigh.dispose();
  24776. }
  24777. target._lodTextureHigh = this._lodTextureHigh;
  24778. }
  24779. if (this._lodTextureMid) {
  24780. if (target._lodTextureMid) {
  24781. target._lodTextureMid.dispose();
  24782. }
  24783. target._lodTextureMid = this._lodTextureMid;
  24784. }
  24785. if (this._lodTextureLow) {
  24786. if (target._lodTextureLow) {
  24787. target._lodTextureLow.dispose();
  24788. }
  24789. target._lodTextureLow = this._lodTextureLow;
  24790. }
  24791. var cache = this._engine.getLoadedTexturesCache();
  24792. var index = cache.indexOf(this);
  24793. if (index !== -1) {
  24794. cache.splice(index, 1);
  24795. }
  24796. };
  24797. /**
  24798. * Dispose the current allocated resources
  24799. */
  24800. InternalTexture.prototype.dispose = function () {
  24801. if (!this._webGLTexture) {
  24802. return;
  24803. }
  24804. this._references--;
  24805. if (this._references === 0) {
  24806. this._engine._releaseTexture(this);
  24807. this._webGLTexture = null;
  24808. this.previous = null;
  24809. this.next = null;
  24810. }
  24811. };
  24812. /**
  24813. * The source of the texture data is unknown
  24814. */
  24815. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24816. /**
  24817. * Texture data comes from an URL
  24818. */
  24819. InternalTexture.DATASOURCE_URL = 1;
  24820. /**
  24821. * Texture data is only used for temporary storage
  24822. */
  24823. InternalTexture.DATASOURCE_TEMP = 2;
  24824. /**
  24825. * Texture data comes from raw data (ArrayBuffer)
  24826. */
  24827. InternalTexture.DATASOURCE_RAW = 3;
  24828. /**
  24829. * Texture content is dynamic (video or dynamic texture)
  24830. */
  24831. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24832. /**
  24833. * Texture content is generated by rendering to it
  24834. */
  24835. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24836. /**
  24837. * Texture content is part of a multi render target process
  24838. */
  24839. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24840. /**
  24841. * Texture data comes from a cube data file
  24842. */
  24843. InternalTexture.DATASOURCE_CUBE = 7;
  24844. /**
  24845. * Texture data comes from a raw cube data
  24846. */
  24847. InternalTexture.DATASOURCE_CUBERAW = 8;
  24848. /**
  24849. * Texture data come from a prefiltered cube data file
  24850. */
  24851. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24852. /**
  24853. * Texture content is raw 3D data
  24854. */
  24855. InternalTexture.DATASOURCE_RAW3D = 10;
  24856. return InternalTexture;
  24857. }());
  24858. BABYLON.InternalTexture = InternalTexture;
  24859. })(BABYLON || (BABYLON = {}));
  24860. //# sourceMappingURL=babylon.internalTexture.js.map
  24861. var BABYLON;
  24862. (function (BABYLON) {
  24863. var BaseTexture = /** @class */ (function () {
  24864. function BaseTexture(scene) {
  24865. this._hasAlpha = false;
  24866. this.getAlphaFromRGB = false;
  24867. this.level = 1;
  24868. this.coordinatesIndex = 0;
  24869. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24870. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24871. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24872. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24873. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24874. this.isCube = false;
  24875. this.is3D = false;
  24876. this.gammaSpace = true;
  24877. this.invertZ = false;
  24878. this.lodLevelInAlpha = false;
  24879. this.lodGenerationOffset = 0.0;
  24880. this.lodGenerationScale = 0.8;
  24881. this.isRenderTarget = false;
  24882. this.animations = new Array();
  24883. /**
  24884. * An event triggered when the texture is disposed.
  24885. * @type {BABYLON.Observable}
  24886. */
  24887. this.onDisposeObservable = new BABYLON.Observable();
  24888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24889. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24890. if (this._scene) {
  24891. this._scene.textures.push(this);
  24892. }
  24893. this._uid = null;
  24894. }
  24895. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24896. get: function () {
  24897. return this._hasAlpha;
  24898. },
  24899. set: function (value) {
  24900. if (this._hasAlpha === value) {
  24901. return;
  24902. }
  24903. this._hasAlpha = value;
  24904. if (this._scene) {
  24905. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  24906. }
  24907. },
  24908. enumerable: true,
  24909. configurable: true
  24910. });
  24911. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24912. get: function () {
  24913. return this._coordinatesMode;
  24914. },
  24915. set: function (value) {
  24916. if (this._coordinatesMode === value) {
  24917. return;
  24918. }
  24919. this._coordinatesMode = value;
  24920. if (this._scene) {
  24921. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24922. }
  24923. },
  24924. enumerable: true,
  24925. configurable: true
  24926. });
  24927. Object.defineProperty(BaseTexture.prototype, "uid", {
  24928. get: function () {
  24929. if (!this._uid) {
  24930. this._uid = BABYLON.Tools.RandomId();
  24931. }
  24932. return this._uid;
  24933. },
  24934. enumerable: true,
  24935. configurable: true
  24936. });
  24937. BaseTexture.prototype.toString = function () {
  24938. return this.name;
  24939. };
  24940. BaseTexture.prototype.getClassName = function () {
  24941. return "BaseTexture";
  24942. };
  24943. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24944. set: function (callback) {
  24945. if (this._onDisposeObserver) {
  24946. this.onDisposeObservable.remove(this._onDisposeObserver);
  24947. }
  24948. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24949. },
  24950. enumerable: true,
  24951. configurable: true
  24952. });
  24953. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24954. get: function () {
  24955. return true;
  24956. },
  24957. enumerable: true,
  24958. configurable: true
  24959. });
  24960. BaseTexture.prototype.getScene = function () {
  24961. return this._scene;
  24962. };
  24963. BaseTexture.prototype.getTextureMatrix = function () {
  24964. return BABYLON.Matrix.IdentityReadOnly;
  24965. };
  24966. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24967. return BABYLON.Matrix.IdentityReadOnly;
  24968. };
  24969. BaseTexture.prototype.getInternalTexture = function () {
  24970. return this._texture;
  24971. };
  24972. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24973. return !this.isBlocking || this.isReady();
  24974. };
  24975. BaseTexture.prototype.isReady = function () {
  24976. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24977. this.delayLoad();
  24978. return false;
  24979. }
  24980. if (this._texture) {
  24981. return this._texture.isReady;
  24982. }
  24983. return false;
  24984. };
  24985. BaseTexture.prototype.getSize = function () {
  24986. if (this._texture && this._texture.width) {
  24987. return new BABYLON.Size(this._texture.width, this._texture.height);
  24988. }
  24989. if (this._texture && this._texture._size) {
  24990. return new BABYLON.Size(this._texture._size, this._texture._size);
  24991. }
  24992. return BABYLON.Size.Zero();
  24993. };
  24994. BaseTexture.prototype.getBaseSize = function () {
  24995. if (!this.isReady() || !this._texture)
  24996. return BABYLON.Size.Zero();
  24997. if (this._texture._size) {
  24998. return new BABYLON.Size(this._texture._size, this._texture._size);
  24999. }
  25000. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25001. };
  25002. BaseTexture.prototype.scale = function (ratio) {
  25003. };
  25004. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25005. get: function () {
  25006. return false;
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25012. if (!this._scene) {
  25013. return null;
  25014. }
  25015. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25016. for (var index = 0; index < texturesCache.length; index++) {
  25017. var texturesCacheEntry = texturesCache[index];
  25018. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25019. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25020. texturesCacheEntry.incrementReferences();
  25021. return texturesCacheEntry;
  25022. }
  25023. }
  25024. }
  25025. return null;
  25026. };
  25027. BaseTexture.prototype._rebuild = function () {
  25028. };
  25029. BaseTexture.prototype.delayLoad = function () {
  25030. };
  25031. BaseTexture.prototype.clone = function () {
  25032. return null;
  25033. };
  25034. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25035. get: function () {
  25036. if (!this._texture) {
  25037. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25038. }
  25039. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25040. },
  25041. enumerable: true,
  25042. configurable: true
  25043. });
  25044. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25045. get: function () {
  25046. if (!this._texture) {
  25047. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25048. }
  25049. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25050. },
  25051. enumerable: true,
  25052. configurable: true
  25053. });
  25054. BaseTexture.prototype.readPixels = function (faceIndex) {
  25055. if (faceIndex === void 0) { faceIndex = 0; }
  25056. if (!this._texture) {
  25057. return null;
  25058. }
  25059. var size = this.getSize();
  25060. var scene = this.getScene();
  25061. if (!scene) {
  25062. return null;
  25063. }
  25064. var engine = scene.getEngine();
  25065. if (this._texture.isCube) {
  25066. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25067. }
  25068. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25069. };
  25070. BaseTexture.prototype.releaseInternalTexture = function () {
  25071. if (this._texture) {
  25072. this._texture.dispose();
  25073. this._texture = null;
  25074. }
  25075. };
  25076. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25077. get: function () {
  25078. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25079. return null;
  25080. }
  25081. if (!this._texture._sphericalPolynomial) {
  25082. this._texture._sphericalPolynomial =
  25083. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25084. }
  25085. return this._texture._sphericalPolynomial;
  25086. },
  25087. set: function (value) {
  25088. if (this._texture) {
  25089. this._texture._sphericalPolynomial = value;
  25090. }
  25091. },
  25092. enumerable: true,
  25093. configurable: true
  25094. });
  25095. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25096. get: function () {
  25097. if (this._texture) {
  25098. return this._texture._lodTextureHigh;
  25099. }
  25100. return null;
  25101. },
  25102. enumerable: true,
  25103. configurable: true
  25104. });
  25105. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25106. get: function () {
  25107. if (this._texture) {
  25108. return this._texture._lodTextureMid;
  25109. }
  25110. return null;
  25111. },
  25112. enumerable: true,
  25113. configurable: true
  25114. });
  25115. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25116. get: function () {
  25117. if (this._texture) {
  25118. return this._texture._lodTextureLow;
  25119. }
  25120. return null;
  25121. },
  25122. enumerable: true,
  25123. configurable: true
  25124. });
  25125. BaseTexture.prototype.dispose = function () {
  25126. if (!this._scene) {
  25127. return;
  25128. }
  25129. // Animations
  25130. this._scene.stopAnimation(this);
  25131. // Remove from scene
  25132. this._scene._removePendingData(this);
  25133. var index = this._scene.textures.indexOf(this);
  25134. if (index >= 0) {
  25135. this._scene.textures.splice(index, 1);
  25136. }
  25137. if (this._texture === undefined) {
  25138. return;
  25139. }
  25140. // Release
  25141. this.releaseInternalTexture();
  25142. // Callback
  25143. this.onDisposeObservable.notifyObservers(this);
  25144. this.onDisposeObservable.clear();
  25145. };
  25146. BaseTexture.prototype.serialize = function () {
  25147. if (!this.name) {
  25148. return null;
  25149. }
  25150. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25151. // Animations
  25152. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25153. return serializationObject;
  25154. };
  25155. BaseTexture.WhenAllReady = function (textures, callback) {
  25156. var numRemaining = textures.length;
  25157. if (numRemaining === 0) {
  25158. callback();
  25159. return;
  25160. }
  25161. var _loop_1 = function () {
  25162. texture = textures[i];
  25163. if (texture.isReady()) {
  25164. if (--numRemaining === 0) {
  25165. callback();
  25166. }
  25167. }
  25168. else {
  25169. onLoadObservable = texture.onLoadObservable;
  25170. var onLoadCallback_1 = function () {
  25171. onLoadObservable.removeCallback(onLoadCallback_1);
  25172. if (--numRemaining === 0) {
  25173. callback();
  25174. }
  25175. };
  25176. onLoadObservable.add(onLoadCallback_1);
  25177. }
  25178. };
  25179. var texture, onLoadObservable;
  25180. for (var i = 0; i < textures.length; i++) {
  25181. _loop_1();
  25182. }
  25183. };
  25184. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25185. __decorate([
  25186. BABYLON.serialize()
  25187. ], BaseTexture.prototype, "name", void 0);
  25188. __decorate([
  25189. BABYLON.serialize("hasAlpha")
  25190. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25191. __decorate([
  25192. BABYLON.serialize()
  25193. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25194. __decorate([
  25195. BABYLON.serialize()
  25196. ], BaseTexture.prototype, "level", void 0);
  25197. __decorate([
  25198. BABYLON.serialize()
  25199. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25200. __decorate([
  25201. BABYLON.serialize("coordinatesMode")
  25202. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25203. __decorate([
  25204. BABYLON.serialize()
  25205. ], BaseTexture.prototype, "wrapU", void 0);
  25206. __decorate([
  25207. BABYLON.serialize()
  25208. ], BaseTexture.prototype, "wrapV", void 0);
  25209. __decorate([
  25210. BABYLON.serialize()
  25211. ], BaseTexture.prototype, "wrapR", void 0);
  25212. __decorate([
  25213. BABYLON.serialize()
  25214. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25215. __decorate([
  25216. BABYLON.serialize()
  25217. ], BaseTexture.prototype, "isCube", void 0);
  25218. __decorate([
  25219. BABYLON.serialize()
  25220. ], BaseTexture.prototype, "is3D", void 0);
  25221. __decorate([
  25222. BABYLON.serialize()
  25223. ], BaseTexture.prototype, "gammaSpace", void 0);
  25224. __decorate([
  25225. BABYLON.serialize()
  25226. ], BaseTexture.prototype, "invertZ", void 0);
  25227. __decorate([
  25228. BABYLON.serialize()
  25229. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25230. __decorate([
  25231. BABYLON.serialize()
  25232. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25233. __decorate([
  25234. BABYLON.serialize()
  25235. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25236. __decorate([
  25237. BABYLON.serialize()
  25238. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25239. return BaseTexture;
  25240. }());
  25241. BABYLON.BaseTexture = BaseTexture;
  25242. })(BABYLON || (BABYLON = {}));
  25243. //# sourceMappingURL=babylon.baseTexture.js.map
  25244. var BABYLON;
  25245. (function (BABYLON) {
  25246. var Texture = /** @class */ (function (_super) {
  25247. __extends(Texture, _super);
  25248. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25249. if (noMipmap === void 0) { noMipmap = false; }
  25250. if (invertY === void 0) { invertY = true; }
  25251. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25252. if (onLoad === void 0) { onLoad = null; }
  25253. if (onError === void 0) { onError = null; }
  25254. if (buffer === void 0) { buffer = null; }
  25255. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25256. var _this = _super.call(this, scene) || this;
  25257. _this.uOffset = 0;
  25258. _this.vOffset = 0;
  25259. _this.uScale = 1.0;
  25260. _this.vScale = 1.0;
  25261. _this.uAng = 0;
  25262. _this.vAng = 0;
  25263. _this.wAng = 0;
  25264. _this._isBlocking = true;
  25265. _this.name = url || "";
  25266. _this.url = url;
  25267. _this._noMipmap = noMipmap;
  25268. _this._invertY = invertY;
  25269. _this._samplingMode = samplingMode;
  25270. _this._buffer = buffer;
  25271. _this._deleteBuffer = deleteBuffer;
  25272. if (format) {
  25273. _this._format = format;
  25274. }
  25275. scene = _this.getScene();
  25276. if (!scene) {
  25277. return _this;
  25278. }
  25279. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25280. var load = function () {
  25281. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25282. _this.onLoadObservable.notifyObservers(_this);
  25283. }
  25284. if (onLoad) {
  25285. onLoad();
  25286. }
  25287. if (!_this.isBlocking && scene) {
  25288. scene.resetCachedMaterial();
  25289. }
  25290. };
  25291. if (!_this.url) {
  25292. _this._delayedOnLoad = load;
  25293. _this._delayedOnError = onError;
  25294. return _this;
  25295. }
  25296. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25297. if (!_this._texture) {
  25298. if (!scene.useDelayedTextureLoading) {
  25299. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25300. if (deleteBuffer) {
  25301. delete _this._buffer;
  25302. }
  25303. }
  25304. else {
  25305. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25306. _this._delayedOnLoad = load;
  25307. _this._delayedOnError = onError;
  25308. }
  25309. }
  25310. else {
  25311. if (_this._texture.isReady) {
  25312. BABYLON.Tools.SetImmediate(function () { return load(); });
  25313. }
  25314. else {
  25315. _this._texture.onLoadedObservable.add(load);
  25316. }
  25317. }
  25318. return _this;
  25319. }
  25320. Object.defineProperty(Texture.prototype, "noMipmap", {
  25321. get: function () {
  25322. return this._noMipmap;
  25323. },
  25324. enumerable: true,
  25325. configurable: true
  25326. });
  25327. Object.defineProperty(Texture.prototype, "isBlocking", {
  25328. get: function () {
  25329. return this._isBlocking;
  25330. },
  25331. set: function (value) {
  25332. this._isBlocking = value;
  25333. },
  25334. enumerable: true,
  25335. configurable: true
  25336. });
  25337. Object.defineProperty(Texture.prototype, "samplingMode", {
  25338. get: function () {
  25339. return this._samplingMode;
  25340. },
  25341. enumerable: true,
  25342. configurable: true
  25343. });
  25344. Texture.prototype.updateURL = function (url) {
  25345. this.url = url;
  25346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25347. this.delayLoad();
  25348. };
  25349. Texture.prototype.delayLoad = function () {
  25350. var _this = this;
  25351. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25352. return;
  25353. }
  25354. var scene = this.getScene();
  25355. if (!scene) {
  25356. return;
  25357. }
  25358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25359. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25360. if (!this._texture) {
  25361. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25362. if (this._deleteBuffer) {
  25363. delete this._buffer;
  25364. }
  25365. }
  25366. else {
  25367. if (this._texture.isReady) {
  25368. BABYLON.Tools.SetImmediate(function () {
  25369. if (!_this._delayedOnLoad) {
  25370. return;
  25371. }
  25372. _this._delayedOnLoad();
  25373. });
  25374. }
  25375. else {
  25376. if (this._delayedOnLoad) {
  25377. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25378. }
  25379. }
  25380. }
  25381. };
  25382. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25383. if (!this._texture) {
  25384. return;
  25385. }
  25386. var scene = this.getScene();
  25387. if (!scene) {
  25388. return;
  25389. }
  25390. this._samplingMode = samplingMode;
  25391. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25392. };
  25393. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25394. x *= this.uScale;
  25395. y *= this.vScale;
  25396. x -= 0.5 * this.uScale;
  25397. y -= 0.5 * this.vScale;
  25398. z -= 0.5;
  25399. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25400. t.x += 0.5 * this.uScale + this.uOffset;
  25401. t.y += 0.5 * this.vScale + this.vOffset;
  25402. t.z += 0.5;
  25403. };
  25404. Texture.prototype.getTextureMatrix = function () {
  25405. var _this = this;
  25406. if (this.uOffset === this._cachedUOffset &&
  25407. this.vOffset === this._cachedVOffset &&
  25408. this.uScale === this._cachedUScale &&
  25409. this.vScale === this._cachedVScale &&
  25410. this.uAng === this._cachedUAng &&
  25411. this.vAng === this._cachedVAng &&
  25412. this.wAng === this._cachedWAng) {
  25413. return this._cachedTextureMatrix;
  25414. }
  25415. this._cachedUOffset = this.uOffset;
  25416. this._cachedVOffset = this.vOffset;
  25417. this._cachedUScale = this.uScale;
  25418. this._cachedVScale = this.vScale;
  25419. this._cachedUAng = this.uAng;
  25420. this._cachedVAng = this.vAng;
  25421. this._cachedWAng = this.wAng;
  25422. if (!this._cachedTextureMatrix) {
  25423. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25424. this._rowGenerationMatrix = new BABYLON.Matrix();
  25425. this._t0 = BABYLON.Vector3.Zero();
  25426. this._t1 = BABYLON.Vector3.Zero();
  25427. this._t2 = BABYLON.Vector3.Zero();
  25428. }
  25429. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25430. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25431. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25432. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25433. this._t1.subtractInPlace(this._t0);
  25434. this._t2.subtractInPlace(this._t0);
  25435. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25436. this._cachedTextureMatrix.m[0] = this._t1.x;
  25437. this._cachedTextureMatrix.m[1] = this._t1.y;
  25438. this._cachedTextureMatrix.m[2] = this._t1.z;
  25439. this._cachedTextureMatrix.m[4] = this._t2.x;
  25440. this._cachedTextureMatrix.m[5] = this._t2.y;
  25441. this._cachedTextureMatrix.m[6] = this._t2.z;
  25442. this._cachedTextureMatrix.m[8] = this._t0.x;
  25443. this._cachedTextureMatrix.m[9] = this._t0.y;
  25444. this._cachedTextureMatrix.m[10] = this._t0.z;
  25445. var scene = this.getScene();
  25446. if (!scene) {
  25447. return this._cachedTextureMatrix;
  25448. }
  25449. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25450. return mat.hasTexture(_this);
  25451. });
  25452. return this._cachedTextureMatrix;
  25453. };
  25454. Texture.prototype.getReflectionTextureMatrix = function () {
  25455. var _this = this;
  25456. var scene = this.getScene();
  25457. if (!scene) {
  25458. return this._cachedTextureMatrix;
  25459. }
  25460. if (this.uOffset === this._cachedUOffset &&
  25461. this.vOffset === this._cachedVOffset &&
  25462. this.uScale === this._cachedUScale &&
  25463. this.vScale === this._cachedVScale &&
  25464. this.coordinatesMode === this._cachedCoordinatesMode) {
  25465. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25466. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25467. return this._cachedTextureMatrix;
  25468. }
  25469. }
  25470. else {
  25471. return this._cachedTextureMatrix;
  25472. }
  25473. }
  25474. if (!this._cachedTextureMatrix) {
  25475. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25476. }
  25477. if (!this._projectionModeMatrix) {
  25478. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25479. }
  25480. this._cachedUOffset = this.uOffset;
  25481. this._cachedVOffset = this.vOffset;
  25482. this._cachedUScale = this.uScale;
  25483. this._cachedVScale = this.vScale;
  25484. this._cachedCoordinatesMode = this.coordinatesMode;
  25485. switch (this.coordinatesMode) {
  25486. case Texture.PLANAR_MODE:
  25487. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25488. this._cachedTextureMatrix[0] = this.uScale;
  25489. this._cachedTextureMatrix[5] = this.vScale;
  25490. this._cachedTextureMatrix[12] = this.uOffset;
  25491. this._cachedTextureMatrix[13] = this.vOffset;
  25492. break;
  25493. case Texture.PROJECTION_MODE:
  25494. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25495. this._projectionModeMatrix.m[0] = 0.5;
  25496. this._projectionModeMatrix.m[5] = -0.5;
  25497. this._projectionModeMatrix.m[10] = 0.0;
  25498. this._projectionModeMatrix.m[12] = 0.5;
  25499. this._projectionModeMatrix.m[13] = 0.5;
  25500. this._projectionModeMatrix.m[14] = 1.0;
  25501. this._projectionModeMatrix.m[15] = 1.0;
  25502. var projectionMatrix = scene.getProjectionMatrix();
  25503. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25504. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25505. break;
  25506. default:
  25507. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25508. break;
  25509. }
  25510. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25511. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25512. });
  25513. return this._cachedTextureMatrix;
  25514. };
  25515. Texture.prototype.clone = function () {
  25516. var _this = this;
  25517. return BABYLON.SerializationHelper.Clone(function () {
  25518. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25519. }, this);
  25520. };
  25521. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25522. get: function () {
  25523. if (!this._onLoadObservable) {
  25524. this._onLoadObservable = new BABYLON.Observable();
  25525. }
  25526. return this._onLoadObservable;
  25527. },
  25528. enumerable: true,
  25529. configurable: true
  25530. });
  25531. Texture.prototype.serialize = function () {
  25532. var serializationObject = _super.prototype.serialize.call(this);
  25533. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25534. serializationObject.base64String = this._buffer;
  25535. serializationObject.name = serializationObject.name.replace("data:", "");
  25536. }
  25537. return serializationObject;
  25538. };
  25539. Texture.prototype.getClassName = function () {
  25540. return "Texture";
  25541. };
  25542. Texture.prototype.dispose = function () {
  25543. _super.prototype.dispose.call(this);
  25544. if (this.onLoadObservable) {
  25545. this.onLoadObservable.clear();
  25546. this._onLoadObservable = null;
  25547. }
  25548. this._delayedOnLoad = null;
  25549. this._delayedOnError = null;
  25550. };
  25551. // Statics
  25552. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25553. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25554. if (onLoad === void 0) { onLoad = null; }
  25555. if (onError === void 0) { onError = null; }
  25556. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25557. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25558. };
  25559. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25560. if (parsedTexture.customType) {
  25561. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25562. // Update Sampling Mode
  25563. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25564. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25565. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25566. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25567. }
  25568. }
  25569. return parsedCustomTexture;
  25570. }
  25571. if (parsedTexture.isCube) {
  25572. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25573. }
  25574. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25575. return null;
  25576. }
  25577. var texture = BABYLON.SerializationHelper.Parse(function () {
  25578. var generateMipMaps = true;
  25579. if (parsedTexture.noMipmap) {
  25580. generateMipMaps = false;
  25581. }
  25582. if (parsedTexture.mirrorPlane) {
  25583. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25584. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25585. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25586. return mirrorTexture;
  25587. }
  25588. else if (parsedTexture.isRenderTarget) {
  25589. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25590. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25591. return renderTargetTexture;
  25592. }
  25593. else {
  25594. var texture;
  25595. if (parsedTexture.base64String) {
  25596. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25597. }
  25598. else {
  25599. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25600. }
  25601. return texture;
  25602. }
  25603. }, parsedTexture, scene);
  25604. // Update Sampling Mode
  25605. if (parsedTexture.samplingMode) {
  25606. var sampling = parsedTexture.samplingMode;
  25607. if (texture._samplingMode !== sampling) {
  25608. texture.updateSamplingMode(sampling);
  25609. }
  25610. }
  25611. // Animations
  25612. if (parsedTexture.animations) {
  25613. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25614. var parsedAnimation = parsedTexture.animations[animationIndex];
  25615. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25616. }
  25617. }
  25618. return texture;
  25619. };
  25620. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25621. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25622. if (noMipmap === void 0) { noMipmap = false; }
  25623. if (invertY === void 0) { invertY = true; }
  25624. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25625. if (onLoad === void 0) { onLoad = null; }
  25626. if (onError === void 0) { onError = null; }
  25627. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25628. if (name.substr(0, 5) !== "data:") {
  25629. name = "data:" + name;
  25630. }
  25631. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25632. };
  25633. // Constants
  25634. Texture.NEAREST_SAMPLINGMODE = 1;
  25635. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25636. Texture.BILINEAR_SAMPLINGMODE = 2;
  25637. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25638. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25639. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25640. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25641. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25642. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25643. Texture.NEAREST_LINEAR = 7;
  25644. Texture.NEAREST_NEAREST = 8;
  25645. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25646. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25647. Texture.LINEAR_LINEAR = 11;
  25648. Texture.LINEAR_NEAREST = 12;
  25649. Texture.EXPLICIT_MODE = 0;
  25650. Texture.SPHERICAL_MODE = 1;
  25651. Texture.PLANAR_MODE = 2;
  25652. Texture.CUBIC_MODE = 3;
  25653. Texture.PROJECTION_MODE = 4;
  25654. Texture.SKYBOX_MODE = 5;
  25655. Texture.INVCUBIC_MODE = 6;
  25656. Texture.EQUIRECTANGULAR_MODE = 7;
  25657. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25658. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25659. Texture.CLAMP_ADDRESSMODE = 0;
  25660. Texture.WRAP_ADDRESSMODE = 1;
  25661. Texture.MIRROR_ADDRESSMODE = 2;
  25662. __decorate([
  25663. BABYLON.serialize()
  25664. ], Texture.prototype, "url", void 0);
  25665. __decorate([
  25666. BABYLON.serialize()
  25667. ], Texture.prototype, "uOffset", void 0);
  25668. __decorate([
  25669. BABYLON.serialize()
  25670. ], Texture.prototype, "vOffset", void 0);
  25671. __decorate([
  25672. BABYLON.serialize()
  25673. ], Texture.prototype, "uScale", void 0);
  25674. __decorate([
  25675. BABYLON.serialize()
  25676. ], Texture.prototype, "vScale", void 0);
  25677. __decorate([
  25678. BABYLON.serialize()
  25679. ], Texture.prototype, "uAng", void 0);
  25680. __decorate([
  25681. BABYLON.serialize()
  25682. ], Texture.prototype, "vAng", void 0);
  25683. __decorate([
  25684. BABYLON.serialize()
  25685. ], Texture.prototype, "wAng", void 0);
  25686. __decorate([
  25687. BABYLON.serialize()
  25688. ], Texture.prototype, "isBlocking", null);
  25689. return Texture;
  25690. }(BABYLON.BaseTexture));
  25691. BABYLON.Texture = Texture;
  25692. })(BABYLON || (BABYLON = {}));
  25693. //# sourceMappingURL=babylon.texture.js.map
  25694. var BABYLON;
  25695. (function (BABYLON) {
  25696. var _InstancesBatch = /** @class */ (function () {
  25697. function _InstancesBatch() {
  25698. this.mustReturn = false;
  25699. this.visibleInstances = new Array();
  25700. this.renderSelf = new Array();
  25701. }
  25702. return _InstancesBatch;
  25703. }());
  25704. BABYLON._InstancesBatch = _InstancesBatch;
  25705. var Mesh = /** @class */ (function (_super) {
  25706. __extends(Mesh, _super);
  25707. /**
  25708. * @constructor
  25709. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25710. * @param {Scene} scene The scene to add this mesh to.
  25711. * @param {Node} parent The parent of this mesh, if it has one
  25712. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25713. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25714. * When false, achieved by calling a clone(), also passing False.
  25715. * This will make creation of children, recursive.
  25716. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25717. */
  25718. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25719. if (scene === void 0) { scene = null; }
  25720. if (parent === void 0) { parent = null; }
  25721. if (source === void 0) { source = null; }
  25722. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25723. var _this = _super.call(this, name, scene) || this;
  25724. // Events
  25725. /**
  25726. * An event triggered before rendering the mesh
  25727. * @type {BABYLON.Observable}
  25728. */
  25729. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25730. /**
  25731. * An event triggered after rendering the mesh
  25732. * @type {BABYLON.Observable}
  25733. */
  25734. _this.onAfterRenderObservable = new BABYLON.Observable();
  25735. /**
  25736. * An event triggered before drawing the mesh
  25737. * @type {BABYLON.Observable}
  25738. */
  25739. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25740. // Members
  25741. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25742. _this.instances = new Array();
  25743. _this._LODLevels = new Array();
  25744. _this._visibleInstances = {};
  25745. _this._renderIdForInstances = new Array();
  25746. _this._batchCache = new _InstancesBatch();
  25747. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25748. // Use by builder only to know what orientation were the mesh build in.
  25749. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25750. _this.overrideMaterialSideOrientation = null;
  25751. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25752. // Will be used to save a source mesh reference, If any
  25753. _this._source = null;
  25754. scene = _this.getScene();
  25755. if (source) {
  25756. // Source mesh
  25757. _this._source = source;
  25758. // Geometry
  25759. if (source._geometry) {
  25760. source._geometry.applyToMesh(_this);
  25761. }
  25762. // Deep copy
  25763. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25764. // Metadata
  25765. if (source.metadata && source.metadata.clone) {
  25766. _this.metadata = source.metadata.clone();
  25767. }
  25768. else {
  25769. _this.metadata = source.metadata;
  25770. }
  25771. // Tags
  25772. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25773. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25774. }
  25775. // Parent
  25776. _this.parent = source.parent;
  25777. // Pivot
  25778. _this.setPivotMatrix(source.getPivotMatrix());
  25779. _this.id = name + "." + source.id;
  25780. // Material
  25781. _this.material = source.material;
  25782. var index;
  25783. if (!doNotCloneChildren) {
  25784. // Children
  25785. var directDescendants = source.getDescendants(true);
  25786. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25787. var child = directDescendants[index_1];
  25788. if (child.clone) {
  25789. child.clone(name + "." + child.name, _this);
  25790. }
  25791. }
  25792. }
  25793. // Physics clone
  25794. var physicsEngine = _this.getScene().getPhysicsEngine();
  25795. if (clonePhysicsImpostor && physicsEngine) {
  25796. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25797. if (impostor) {
  25798. _this.physicsImpostor = impostor.clone(_this);
  25799. }
  25800. }
  25801. // Particles
  25802. for (index = 0; index < scene.particleSystems.length; index++) {
  25803. var system = scene.particleSystems[index];
  25804. if (system.emitter === source) {
  25805. system.clone(system.name, _this);
  25806. }
  25807. }
  25808. _this.computeWorldMatrix(true);
  25809. }
  25810. // Parent
  25811. if (parent !== null) {
  25812. _this.parent = parent;
  25813. }
  25814. return _this;
  25815. }
  25816. Object.defineProperty(Mesh, "FRONTSIDE", {
  25817. /**
  25818. * Mesh side orientation : usually the external or front surface
  25819. */
  25820. get: function () {
  25821. return Mesh._FRONTSIDE;
  25822. },
  25823. enumerable: true,
  25824. configurable: true
  25825. });
  25826. Object.defineProperty(Mesh, "BACKSIDE", {
  25827. /**
  25828. * Mesh side orientation : usually the internal or back surface
  25829. */
  25830. get: function () {
  25831. return Mesh._BACKSIDE;
  25832. },
  25833. enumerable: true,
  25834. configurable: true
  25835. });
  25836. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25837. /**
  25838. * Mesh side orientation : both internal and external or front and back surfaces
  25839. */
  25840. get: function () {
  25841. return Mesh._DOUBLESIDE;
  25842. },
  25843. enumerable: true,
  25844. configurable: true
  25845. });
  25846. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25847. /**
  25848. * Mesh side orientation : by default, `FRONTSIDE`
  25849. */
  25850. get: function () {
  25851. return Mesh._DEFAULTSIDE;
  25852. },
  25853. enumerable: true,
  25854. configurable: true
  25855. });
  25856. Object.defineProperty(Mesh, "NO_CAP", {
  25857. /**
  25858. * Mesh cap setting : no cap
  25859. */
  25860. get: function () {
  25861. return Mesh._NO_CAP;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(Mesh, "CAP_START", {
  25867. /**
  25868. * Mesh cap setting : one cap at the beginning of the mesh
  25869. */
  25870. get: function () {
  25871. return Mesh._CAP_START;
  25872. },
  25873. enumerable: true,
  25874. configurable: true
  25875. });
  25876. Object.defineProperty(Mesh, "CAP_END", {
  25877. /**
  25878. * Mesh cap setting : one cap at the end of the mesh
  25879. */
  25880. get: function () {
  25881. return Mesh._CAP_END;
  25882. },
  25883. enumerable: true,
  25884. configurable: true
  25885. });
  25886. Object.defineProperty(Mesh, "CAP_ALL", {
  25887. /**
  25888. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25889. */
  25890. get: function () {
  25891. return Mesh._CAP_ALL;
  25892. },
  25893. enumerable: true,
  25894. configurable: true
  25895. });
  25896. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25897. set: function (callback) {
  25898. if (this._onBeforeDrawObserver) {
  25899. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25900. }
  25901. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25902. },
  25903. enumerable: true,
  25904. configurable: true
  25905. });
  25906. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25907. get: function () {
  25908. return this._morphTargetManager;
  25909. },
  25910. set: function (value) {
  25911. if (this._morphTargetManager === value) {
  25912. return;
  25913. }
  25914. this._morphTargetManager = value;
  25915. this._syncGeometryWithMorphTargetManager();
  25916. },
  25917. enumerable: true,
  25918. configurable: true
  25919. });
  25920. Object.defineProperty(Mesh.prototype, "source", {
  25921. get: function () {
  25922. return this._source;
  25923. },
  25924. enumerable: true,
  25925. configurable: true
  25926. });
  25927. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25928. get: function () {
  25929. return this._unIndexed;
  25930. },
  25931. set: function (value) {
  25932. if (this._unIndexed !== value) {
  25933. this._unIndexed = value;
  25934. this._markSubMeshesAsAttributesDirty();
  25935. }
  25936. },
  25937. enumerable: true,
  25938. configurable: true
  25939. });
  25940. // Methods
  25941. /**
  25942. * Returns the string "Mesh".
  25943. */
  25944. Mesh.prototype.getClassName = function () {
  25945. return "Mesh";
  25946. };
  25947. /**
  25948. * Returns a string.
  25949. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25950. */
  25951. Mesh.prototype.toString = function (fullDetails) {
  25952. var ret = _super.prototype.toString.call(this, fullDetails);
  25953. ret += ", n vertices: " + this.getTotalVertices();
  25954. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25955. if (this.animations) {
  25956. for (var i = 0; i < this.animations.length; i++) {
  25957. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25958. }
  25959. }
  25960. if (fullDetails) {
  25961. if (this._geometry) {
  25962. var ib = this.getIndices();
  25963. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25964. if (vb && ib) {
  25965. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25966. }
  25967. }
  25968. else {
  25969. ret += ", flat shading: UNKNOWN";
  25970. }
  25971. }
  25972. return ret;
  25973. };
  25974. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25975. /**
  25976. * True if the mesh has some Levels Of Details (LOD).
  25977. * Returns a boolean.
  25978. */
  25979. get: function () {
  25980. return this._LODLevels.length > 0;
  25981. },
  25982. enumerable: true,
  25983. configurable: true
  25984. });
  25985. /**
  25986. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25987. * @returns an array of {BABYLON.MeshLODLevel}
  25988. */
  25989. Mesh.prototype.getLODLevels = function () {
  25990. return this._LODLevels;
  25991. };
  25992. Mesh.prototype._sortLODLevels = function () {
  25993. this._LODLevels.sort(function (a, b) {
  25994. if (a.distance < b.distance) {
  25995. return 1;
  25996. }
  25997. if (a.distance > b.distance) {
  25998. return -1;
  25999. }
  26000. return 0;
  26001. });
  26002. };
  26003. /**
  26004. * Add a mesh as LOD level triggered at the given distance.
  26005. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26006. * @param {number} distance The distance from the center of the object to show this level
  26007. * @param {Mesh} mesh The mesh to be added as LOD level
  26008. * @return {Mesh} This mesh (for chaining)
  26009. */
  26010. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26011. if (mesh && mesh._masterMesh) {
  26012. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26013. return this;
  26014. }
  26015. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26016. this._LODLevels.push(level);
  26017. if (mesh) {
  26018. mesh._masterMesh = this;
  26019. }
  26020. this._sortLODLevels();
  26021. return this;
  26022. };
  26023. /**
  26024. * Returns the LOD level mesh at the passed distance or null if not found.
  26025. * It is related to the method `addLODLevel(distance, mesh)`.
  26026. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26027. * Returns an object Mesh or `null`.
  26028. */
  26029. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26030. for (var index = 0; index < this._LODLevels.length; index++) {
  26031. var level = this._LODLevels[index];
  26032. if (level.distance === distance) {
  26033. return level.mesh;
  26034. }
  26035. }
  26036. return null;
  26037. };
  26038. /**
  26039. * Remove a mesh from the LOD array
  26040. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26041. * @param {Mesh} mesh The mesh to be removed.
  26042. * @return {Mesh} This mesh (for chaining)
  26043. */
  26044. Mesh.prototype.removeLODLevel = function (mesh) {
  26045. for (var index = 0; index < this._LODLevels.length; index++) {
  26046. if (this._LODLevels[index].mesh === mesh) {
  26047. this._LODLevels.splice(index, 1);
  26048. if (mesh) {
  26049. mesh._masterMesh = null;
  26050. }
  26051. }
  26052. }
  26053. this._sortLODLevels();
  26054. return this;
  26055. };
  26056. /**
  26057. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26058. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26059. */
  26060. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26061. if (!this._LODLevels || this._LODLevels.length === 0) {
  26062. return this;
  26063. }
  26064. var bSphere;
  26065. if (boundingSphere) {
  26066. bSphere = boundingSphere;
  26067. }
  26068. else {
  26069. var boundingInfo = this.getBoundingInfo();
  26070. bSphere = boundingInfo.boundingSphere;
  26071. }
  26072. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26073. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26074. if (this.onLODLevelSelection) {
  26075. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26076. }
  26077. return this;
  26078. }
  26079. for (var index = 0; index < this._LODLevels.length; index++) {
  26080. var level = this._LODLevels[index];
  26081. if (level.distance < distanceToCamera) {
  26082. if (level.mesh) {
  26083. level.mesh._preActivate();
  26084. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26085. }
  26086. if (this.onLODLevelSelection) {
  26087. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26088. }
  26089. return level.mesh;
  26090. }
  26091. }
  26092. if (this.onLODLevelSelection) {
  26093. this.onLODLevelSelection(distanceToCamera, this, this);
  26094. }
  26095. return this;
  26096. };
  26097. Object.defineProperty(Mesh.prototype, "geometry", {
  26098. /**
  26099. * Returns the mesh internal Geometry object.
  26100. */
  26101. get: function () {
  26102. return this._geometry;
  26103. },
  26104. enumerable: true,
  26105. configurable: true
  26106. });
  26107. /**
  26108. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26109. */
  26110. Mesh.prototype.getTotalVertices = function () {
  26111. if (this._geometry === null || this._geometry === undefined) {
  26112. return 0;
  26113. }
  26114. return this._geometry.getTotalVertices();
  26115. };
  26116. /**
  26117. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26118. * 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.
  26119. * You can force the copy with forceCopy === true
  26120. * Returns null if the mesh has no geometry or no vertex buffer.
  26121. * Possible `kind` values :
  26122. * - BABYLON.VertexBuffer.PositionKind
  26123. * - BABYLON.VertexBuffer.UVKind
  26124. * - BABYLON.VertexBuffer.UV2Kind
  26125. * - BABYLON.VertexBuffer.UV3Kind
  26126. * - BABYLON.VertexBuffer.UV4Kind
  26127. * - BABYLON.VertexBuffer.UV5Kind
  26128. * - BABYLON.VertexBuffer.UV6Kind
  26129. * - BABYLON.VertexBuffer.ColorKind
  26130. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26131. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26132. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26133. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26134. */
  26135. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26136. if (!this._geometry) {
  26137. return null;
  26138. }
  26139. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26140. };
  26141. /**
  26142. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26143. * Returns `null` if the mesh has no geometry.
  26144. * Possible `kind` values :
  26145. * - BABYLON.VertexBuffer.PositionKind
  26146. * - BABYLON.VertexBuffer.UVKind
  26147. * - BABYLON.VertexBuffer.UV2Kind
  26148. * - BABYLON.VertexBuffer.UV3Kind
  26149. * - BABYLON.VertexBuffer.UV4Kind
  26150. * - BABYLON.VertexBuffer.UV5Kind
  26151. * - BABYLON.VertexBuffer.UV6Kind
  26152. * - BABYLON.VertexBuffer.ColorKind
  26153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26157. */
  26158. Mesh.prototype.getVertexBuffer = function (kind) {
  26159. if (!this._geometry) {
  26160. return null;
  26161. }
  26162. return this._geometry.getVertexBuffer(kind);
  26163. };
  26164. /**
  26165. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26166. * Possible `kind` values :
  26167. * - BABYLON.VertexBuffer.PositionKind
  26168. * - BABYLON.VertexBuffer.UVKind
  26169. * - BABYLON.VertexBuffer.UV2Kind
  26170. * - BABYLON.VertexBuffer.UV3Kind
  26171. * - BABYLON.VertexBuffer.UV4Kind
  26172. * - BABYLON.VertexBuffer.UV5Kind
  26173. * - BABYLON.VertexBuffer.UV6Kind
  26174. * - BABYLON.VertexBuffer.ColorKind
  26175. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26176. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26177. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26178. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26179. */
  26180. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26181. if (!this._geometry) {
  26182. if (this._delayInfo) {
  26183. return this._delayInfo.indexOf(kind) !== -1;
  26184. }
  26185. return false;
  26186. }
  26187. return this._geometry.isVerticesDataPresent(kind);
  26188. };
  26189. /**
  26190. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26191. * Possible `kind` values :
  26192. * - BABYLON.VertexBuffer.PositionKind
  26193. * - BABYLON.VertexBuffer.UVKind
  26194. * - BABYLON.VertexBuffer.UV2Kind
  26195. * - BABYLON.VertexBuffer.UV3Kind
  26196. * - BABYLON.VertexBuffer.UV4Kind
  26197. * - BABYLON.VertexBuffer.UV5Kind
  26198. * - BABYLON.VertexBuffer.UV6Kind
  26199. * - BABYLON.VertexBuffer.ColorKind
  26200. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26201. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26202. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26203. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26204. */
  26205. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26206. if (!this._geometry) {
  26207. if (this._delayInfo) {
  26208. return this._delayInfo.indexOf(kind) !== -1;
  26209. }
  26210. return false;
  26211. }
  26212. return this._geometry.isVertexBufferUpdatable(kind);
  26213. };
  26214. /**
  26215. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26216. * Possible `kind` values :
  26217. * - BABYLON.VertexBuffer.PositionKind
  26218. * - BABYLON.VertexBuffer.UVKind
  26219. * - BABYLON.VertexBuffer.UV2Kind
  26220. * - BABYLON.VertexBuffer.UV3Kind
  26221. * - BABYLON.VertexBuffer.UV4Kind
  26222. * - BABYLON.VertexBuffer.UV5Kind
  26223. * - BABYLON.VertexBuffer.UV6Kind
  26224. * - BABYLON.VertexBuffer.ColorKind
  26225. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26226. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26227. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26228. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26229. */
  26230. Mesh.prototype.getVerticesDataKinds = function () {
  26231. if (!this._geometry) {
  26232. var result = new Array();
  26233. if (this._delayInfo) {
  26234. this._delayInfo.forEach(function (kind, index, array) {
  26235. result.push(kind);
  26236. });
  26237. }
  26238. return result;
  26239. }
  26240. return this._geometry.getVerticesDataKinds();
  26241. };
  26242. /**
  26243. * Returns a positive integer : the total number of indices in this mesh geometry.
  26244. * Returns zero if the mesh has no geometry.
  26245. */
  26246. Mesh.prototype.getTotalIndices = function () {
  26247. if (!this._geometry) {
  26248. return 0;
  26249. }
  26250. return this._geometry.getTotalIndices();
  26251. };
  26252. /**
  26253. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26254. * 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.
  26255. * Returns an empty array if the mesh has no geometry.
  26256. */
  26257. Mesh.prototype.getIndices = function (copyWhenShared) {
  26258. if (!this._geometry) {
  26259. return [];
  26260. }
  26261. return this._geometry.getIndices(copyWhenShared);
  26262. };
  26263. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26264. get: function () {
  26265. return this._masterMesh !== null && this._masterMesh !== undefined;
  26266. },
  26267. enumerable: true,
  26268. configurable: true
  26269. });
  26270. /**
  26271. * Determine if the current mesh is ready to be rendered
  26272. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26273. * @returns true if all associated assets are ready (material, textures, shaders)
  26274. */
  26275. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26276. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26277. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26278. return false;
  26279. }
  26280. if (!_super.prototype.isReady.call(this)) {
  26281. return false;
  26282. }
  26283. if (!this.subMeshes || this.subMeshes.length === 0) {
  26284. return true;
  26285. }
  26286. var engine = this.getEngine();
  26287. var scene = this.getScene();
  26288. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26289. this.computeWorldMatrix();
  26290. var mat = this.material || scene.defaultMaterial;
  26291. if (mat) {
  26292. if (mat.storeEffectOnSubMeshes) {
  26293. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26294. var subMesh = _a[_i];
  26295. var effectiveMaterial = subMesh.getMaterial();
  26296. if (effectiveMaterial) {
  26297. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26298. return false;
  26299. }
  26300. }
  26301. }
  26302. }
  26303. else {
  26304. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26305. return false;
  26306. }
  26307. }
  26308. }
  26309. // Shadows
  26310. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26311. var light = _c[_b];
  26312. var generator = light.getShadowGenerator();
  26313. if (generator) {
  26314. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26315. var subMesh = _e[_d];
  26316. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26317. return false;
  26318. }
  26319. }
  26320. }
  26321. }
  26322. // LOD
  26323. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26324. var lod = _g[_f];
  26325. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26326. return false;
  26327. }
  26328. }
  26329. return true;
  26330. };
  26331. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26332. /**
  26333. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26334. * This property is pertinent only for updatable parametric shapes.
  26335. */
  26336. get: function () {
  26337. return this._areNormalsFrozen;
  26338. },
  26339. enumerable: true,
  26340. configurable: true
  26341. });
  26342. /**
  26343. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26344. * It has no effect at all on other shapes.
  26345. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26346. * Returns the Mesh.
  26347. */
  26348. Mesh.prototype.freezeNormals = function () {
  26349. this._areNormalsFrozen = true;
  26350. return this;
  26351. };
  26352. /**
  26353. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26354. * It has no effect at all on other shapes.
  26355. * It reactivates the mesh normals computation if it was previously frozen.
  26356. * Returns the Mesh.
  26357. */
  26358. Mesh.prototype.unfreezeNormals = function () {
  26359. this._areNormalsFrozen = false;
  26360. return this;
  26361. };
  26362. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26363. /**
  26364. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26365. */
  26366. set: function (count) {
  26367. this._overridenInstanceCount = count;
  26368. },
  26369. enumerable: true,
  26370. configurable: true
  26371. });
  26372. // Methods
  26373. Mesh.prototype._preActivate = function () {
  26374. var sceneRenderId = this.getScene().getRenderId();
  26375. if (this._preActivateId === sceneRenderId) {
  26376. return this;
  26377. }
  26378. this._preActivateId = sceneRenderId;
  26379. this._visibleInstances = null;
  26380. return this;
  26381. };
  26382. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26383. if (this._visibleInstances) {
  26384. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26385. }
  26386. return this;
  26387. };
  26388. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26389. if (!this._visibleInstances) {
  26390. this._visibleInstances = {};
  26391. this._visibleInstances.defaultRenderId = renderId;
  26392. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26393. }
  26394. if (!this._visibleInstances[renderId]) {
  26395. this._visibleInstances[renderId] = new Array();
  26396. }
  26397. this._visibleInstances[renderId].push(instance);
  26398. return this;
  26399. };
  26400. /**
  26401. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26402. * This means the mesh underlying bounding box and sphere are recomputed.
  26403. * Returns the Mesh.
  26404. */
  26405. Mesh.prototype.refreshBoundingInfo = function () {
  26406. return this._refreshBoundingInfo(false);
  26407. };
  26408. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26409. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26410. return this;
  26411. }
  26412. var data = this._getPositionData(applySkeleton);
  26413. if (data) {
  26414. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26415. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26416. }
  26417. if (this.subMeshes) {
  26418. for (var index = 0; index < this.subMeshes.length; index++) {
  26419. this.subMeshes[index].refreshBoundingInfo();
  26420. }
  26421. }
  26422. this._updateBoundingInfo();
  26423. return this;
  26424. };
  26425. Mesh.prototype._getPositionData = function (applySkeleton) {
  26426. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26427. if (data && applySkeleton && this.skeleton) {
  26428. data = BABYLON.Tools.Slice(data);
  26429. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26430. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26431. if (matricesWeightsData && matricesIndicesData) {
  26432. var needExtras = this.numBoneInfluencers > 4;
  26433. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26434. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26435. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26436. var tempVector = BABYLON.Tmp.Vector3[0];
  26437. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26438. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26439. var matWeightIdx = 0;
  26440. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26441. finalMatrix.reset();
  26442. var inf;
  26443. var weight;
  26444. for (inf = 0; inf < 4; inf++) {
  26445. weight = matricesWeightsData[matWeightIdx + inf];
  26446. if (weight <= 0)
  26447. break;
  26448. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26449. finalMatrix.addToSelf(tempMatrix);
  26450. }
  26451. if (needExtras) {
  26452. for (inf = 0; inf < 4; inf++) {
  26453. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26454. if (weight <= 0)
  26455. break;
  26456. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26457. finalMatrix.addToSelf(tempMatrix);
  26458. }
  26459. }
  26460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26461. tempVector.toArray(data, index);
  26462. }
  26463. }
  26464. }
  26465. return data;
  26466. };
  26467. Mesh.prototype._createGlobalSubMesh = function (force) {
  26468. var totalVertices = this.getTotalVertices();
  26469. if (!totalVertices || !this.getIndices()) {
  26470. return null;
  26471. }
  26472. // Check if we need to recreate the submeshes
  26473. if (this.subMeshes && this.subMeshes.length > 0) {
  26474. var ib = this.getIndices();
  26475. if (!ib) {
  26476. return null;
  26477. }
  26478. var totalIndices = ib.length;
  26479. var needToRecreate = false;
  26480. if (force) {
  26481. needToRecreate = true;
  26482. }
  26483. else {
  26484. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26485. var submesh = _a[_i];
  26486. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26487. needToRecreate = true;
  26488. break;
  26489. }
  26490. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26491. needToRecreate = true;
  26492. break;
  26493. }
  26494. }
  26495. }
  26496. if (!needToRecreate) {
  26497. return this.subMeshes[0];
  26498. }
  26499. }
  26500. this.releaseSubMeshes();
  26501. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26502. };
  26503. Mesh.prototype.subdivide = function (count) {
  26504. if (count < 1) {
  26505. return;
  26506. }
  26507. var totalIndices = this.getTotalIndices();
  26508. var subdivisionSize = (totalIndices / count) | 0;
  26509. var offset = 0;
  26510. // Ensure that subdivisionSize is a multiple of 3
  26511. while (subdivisionSize % 3 !== 0) {
  26512. subdivisionSize++;
  26513. }
  26514. this.releaseSubMeshes();
  26515. for (var index = 0; index < count; index++) {
  26516. if (offset >= totalIndices) {
  26517. break;
  26518. }
  26519. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26520. offset += subdivisionSize;
  26521. }
  26522. this.synchronizeInstances();
  26523. };
  26524. /**
  26525. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26526. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26527. * The `data` are either a numeric array either a Float32Array.
  26528. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26529. * 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).
  26530. * Note that a new underlying VertexBuffer object is created each call.
  26531. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26532. *
  26533. * Possible `kind` values :
  26534. * - BABYLON.VertexBuffer.PositionKind
  26535. * - BABYLON.VertexBuffer.UVKind
  26536. * - BABYLON.VertexBuffer.UV2Kind
  26537. * - BABYLON.VertexBuffer.UV3Kind
  26538. * - BABYLON.VertexBuffer.UV4Kind
  26539. * - BABYLON.VertexBuffer.UV5Kind
  26540. * - BABYLON.VertexBuffer.UV6Kind
  26541. * - BABYLON.VertexBuffer.ColorKind
  26542. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26543. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26544. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26545. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26546. *
  26547. * Returns the Mesh.
  26548. */
  26549. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26550. if (updatable === void 0) { updatable = false; }
  26551. if (!this._geometry) {
  26552. var vertexData = new BABYLON.VertexData();
  26553. vertexData.set(data, kind);
  26554. var scene = this.getScene();
  26555. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26556. }
  26557. else {
  26558. this._geometry.setVerticesData(kind, data, updatable, stride);
  26559. }
  26560. return this;
  26561. };
  26562. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26563. if (updatable === void 0) { updatable = true; }
  26564. var vb = this.getVertexBuffer(kind);
  26565. if (!vb || vb.isUpdatable() === updatable) {
  26566. return;
  26567. }
  26568. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26569. };
  26570. /**
  26571. * Sets the mesh VertexBuffer.
  26572. * Returns the Mesh.
  26573. */
  26574. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26575. if (!this._geometry) {
  26576. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26577. }
  26578. this._geometry.setVerticesBuffer(buffer);
  26579. return this;
  26580. };
  26581. /**
  26582. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26583. * If the mesh has no geometry, it is simply returned as it is.
  26584. * The `data` are either a numeric array either a Float32Array.
  26585. * No new underlying VertexBuffer object is created.
  26586. * 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.
  26587. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26588. *
  26589. * Possible `kind` values :
  26590. * - BABYLON.VertexBuffer.PositionKind
  26591. * - BABYLON.VertexBuffer.UVKind
  26592. * - BABYLON.VertexBuffer.UV2Kind
  26593. * - BABYLON.VertexBuffer.UV3Kind
  26594. * - BABYLON.VertexBuffer.UV4Kind
  26595. * - BABYLON.VertexBuffer.UV5Kind
  26596. * - BABYLON.VertexBuffer.UV6Kind
  26597. * - BABYLON.VertexBuffer.ColorKind
  26598. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26599. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26600. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26601. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26602. *
  26603. * Returns the Mesh.
  26604. */
  26605. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26606. if (!this._geometry) {
  26607. return this;
  26608. }
  26609. if (!makeItUnique) {
  26610. this._geometry.updateVerticesData(kind, data, updateExtends);
  26611. }
  26612. else {
  26613. this.makeGeometryUnique();
  26614. this.updateVerticesData(kind, data, updateExtends, false);
  26615. }
  26616. return this;
  26617. };
  26618. /**
  26619. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26620. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26621. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26622. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26623. * Returns the Mesh.
  26624. */
  26625. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26626. if (computeNormals === void 0) { computeNormals = true; }
  26627. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26628. if (!positions) {
  26629. return this;
  26630. }
  26631. positionFunction(positions);
  26632. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26633. if (computeNormals) {
  26634. var indices = this.getIndices();
  26635. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26636. if (!normals) {
  26637. return this;
  26638. }
  26639. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26640. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26641. }
  26642. return this;
  26643. };
  26644. /**
  26645. * Creates a un-shared specific occurence of the geometry for the mesh.
  26646. * Returns the Mesh.
  26647. */
  26648. Mesh.prototype.makeGeometryUnique = function () {
  26649. if (!this._geometry) {
  26650. return this;
  26651. }
  26652. var oldGeometry = this._geometry;
  26653. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26654. oldGeometry.releaseForMesh(this, true);
  26655. geometry.applyToMesh(this);
  26656. return this;
  26657. };
  26658. /**
  26659. * Sets the mesh indices.
  26660. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26661. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26662. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26663. * This method creates a new index buffer each call.
  26664. * Returns the Mesh.
  26665. */
  26666. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26667. if (totalVertices === void 0) { totalVertices = null; }
  26668. if (updatable === void 0) { updatable = false; }
  26669. if (!this._geometry) {
  26670. var vertexData = new BABYLON.VertexData();
  26671. vertexData.indices = indices;
  26672. var scene = this.getScene();
  26673. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26674. }
  26675. else {
  26676. this._geometry.setIndices(indices, totalVertices, updatable);
  26677. }
  26678. return this;
  26679. };
  26680. /**
  26681. * Update the current index buffer
  26682. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26683. * Returns the Mesh.
  26684. */
  26685. Mesh.prototype.updateIndices = function (indices, offset) {
  26686. if (!this._geometry) {
  26687. return this;
  26688. }
  26689. this._geometry.updateIndices(indices, offset);
  26690. return this;
  26691. };
  26692. /**
  26693. * Invert the geometry to move from a right handed system to a left handed one.
  26694. * Returns the Mesh.
  26695. */
  26696. Mesh.prototype.toLeftHanded = function () {
  26697. if (!this._geometry) {
  26698. return this;
  26699. }
  26700. this._geometry.toLeftHanded();
  26701. return this;
  26702. };
  26703. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26704. if (!this._geometry) {
  26705. return this;
  26706. }
  26707. var engine = this.getScene().getEngine();
  26708. // Wireframe
  26709. var indexToBind;
  26710. if (this._unIndexed) {
  26711. indexToBind = null;
  26712. }
  26713. else {
  26714. switch (fillMode) {
  26715. case BABYLON.Material.PointFillMode:
  26716. indexToBind = null;
  26717. break;
  26718. case BABYLON.Material.WireFrameFillMode:
  26719. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26720. break;
  26721. default:
  26722. case BABYLON.Material.TriangleFillMode:
  26723. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26724. break;
  26725. }
  26726. }
  26727. // VBOs
  26728. this._geometry._bind(effect, indexToBind);
  26729. return this;
  26730. };
  26731. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26732. if (alternate === void 0) { alternate = false; }
  26733. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26734. return this;
  26735. }
  26736. this.onBeforeDrawObservable.notifyObservers(this);
  26737. var scene = this.getScene();
  26738. var engine = scene.getEngine();
  26739. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26740. // or triangles as points
  26741. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26742. }
  26743. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26744. // Triangles as wireframe
  26745. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26746. }
  26747. else {
  26748. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26749. }
  26750. if (scene._isAlternateRenderingEnabled && !alternate) {
  26751. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26752. if (!effect || !scene.activeCamera) {
  26753. return this;
  26754. }
  26755. scene._switchToAlternateCameraConfiguration(true);
  26756. this._effectiveMaterial.bindView(effect);
  26757. this._effectiveMaterial.bindViewProjection(effect);
  26758. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26759. this._draw(subMesh, fillMode, instancesCount, true);
  26760. engine.setViewport(scene.activeCamera.viewport);
  26761. scene._switchToAlternateCameraConfiguration(false);
  26762. this._effectiveMaterial.bindView(effect);
  26763. this._effectiveMaterial.bindViewProjection(effect);
  26764. }
  26765. return this;
  26766. };
  26767. /**
  26768. * Registers for this mesh a javascript function called just before the rendering process.
  26769. * This function is passed the current mesh.
  26770. * Return the Mesh.
  26771. */
  26772. Mesh.prototype.registerBeforeRender = function (func) {
  26773. this.onBeforeRenderObservable.add(func);
  26774. return this;
  26775. };
  26776. /**
  26777. * Disposes a previously registered javascript function called before the rendering.
  26778. * This function is passed the current mesh.
  26779. * Returns the Mesh.
  26780. */
  26781. Mesh.prototype.unregisterBeforeRender = function (func) {
  26782. this.onBeforeRenderObservable.removeCallback(func);
  26783. return this;
  26784. };
  26785. /**
  26786. * Registers for this mesh a javascript function called just after the rendering is complete.
  26787. * This function is passed the current mesh.
  26788. * Returns the Mesh.
  26789. */
  26790. Mesh.prototype.registerAfterRender = function (func) {
  26791. this.onAfterRenderObservable.add(func);
  26792. return this;
  26793. };
  26794. /**
  26795. * Disposes a previously registered javascript function called after the rendering.
  26796. * This function is passed the current mesh.
  26797. * Return the Mesh.
  26798. */
  26799. Mesh.prototype.unregisterAfterRender = function (func) {
  26800. this.onAfterRenderObservable.removeCallback(func);
  26801. return this;
  26802. };
  26803. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26804. var scene = this.getScene();
  26805. this._batchCache.mustReturn = false;
  26806. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26807. this._batchCache.visibleInstances[subMeshId] = null;
  26808. if (this._visibleInstances) {
  26809. var currentRenderId = scene.getRenderId();
  26810. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26811. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26812. var selfRenderId = this._renderId;
  26813. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26814. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26815. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26816. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26817. }
  26818. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26819. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26820. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26821. this._batchCache.mustReturn = true;
  26822. return this._batchCache;
  26823. }
  26824. if (currentRenderId !== selfRenderId) {
  26825. this._batchCache.renderSelf[subMeshId] = false;
  26826. }
  26827. }
  26828. this._renderIdForInstances[subMeshId] = currentRenderId;
  26829. }
  26830. return this._batchCache;
  26831. };
  26832. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26833. var visibleInstances = batch.visibleInstances[subMesh._id];
  26834. if (!visibleInstances) {
  26835. return this;
  26836. }
  26837. var matricesCount = visibleInstances.length + 1;
  26838. var bufferSize = matricesCount * 16 * 4;
  26839. var currentInstancesBufferSize = this._instancesBufferSize;
  26840. var instancesBuffer = this._instancesBuffer;
  26841. while (this._instancesBufferSize < bufferSize) {
  26842. this._instancesBufferSize *= 2;
  26843. }
  26844. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26845. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26846. }
  26847. var offset = 0;
  26848. var instancesCount = 0;
  26849. var world = this.getWorldMatrix();
  26850. if (batch.renderSelf[subMesh._id]) {
  26851. world.copyToArray(this._instancesData, offset);
  26852. offset += 16;
  26853. instancesCount++;
  26854. }
  26855. if (visibleInstances) {
  26856. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26857. var instance = visibleInstances[instanceIndex];
  26858. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26859. offset += 16;
  26860. instancesCount++;
  26861. }
  26862. }
  26863. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26864. if (instancesBuffer) {
  26865. instancesBuffer.dispose();
  26866. }
  26867. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26868. this._instancesBuffer = instancesBuffer;
  26869. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26870. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26871. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26872. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26873. }
  26874. else {
  26875. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26876. }
  26877. this._bind(subMesh, effect, fillMode);
  26878. this._draw(subMesh, fillMode, instancesCount);
  26879. engine.unbindInstanceAttributes();
  26880. return this;
  26881. };
  26882. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26883. var scene = this.getScene();
  26884. var engine = scene.getEngine();
  26885. if (hardwareInstancedRendering) {
  26886. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26887. }
  26888. else {
  26889. if (batch.renderSelf[subMesh._id]) {
  26890. // Draw
  26891. if (onBeforeDraw) {
  26892. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26893. }
  26894. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26895. }
  26896. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26897. if (visibleInstancesForSubMesh) {
  26898. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26899. var instance = visibleInstancesForSubMesh[instanceIndex];
  26900. // World
  26901. var world = instance.getWorldMatrix();
  26902. if (onBeforeDraw) {
  26903. onBeforeDraw(true, world, effectiveMaterial);
  26904. }
  26905. // Draw
  26906. this._draw(subMesh, fillMode);
  26907. }
  26908. }
  26909. }
  26910. return this;
  26911. };
  26912. /**
  26913. * Triggers the draw call for the mesh.
  26914. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26915. * Returns the Mesh.
  26916. */
  26917. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26918. this.checkOcclusionQuery();
  26919. if (this._isOccluded) {
  26920. return this;
  26921. }
  26922. var scene = this.getScene();
  26923. // Managing instances
  26924. var batch = this._getInstancesRenderList(subMesh._id);
  26925. if (batch.mustReturn) {
  26926. return this;
  26927. }
  26928. // Checking geometry state
  26929. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26930. return this;
  26931. }
  26932. this.onBeforeRenderObservable.notifyObservers(this);
  26933. var engine = scene.getEngine();
  26934. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26935. // Material
  26936. var material = subMesh.getMaterial();
  26937. if (!material) {
  26938. return this;
  26939. }
  26940. this._effectiveMaterial = material;
  26941. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26942. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26943. return this;
  26944. }
  26945. }
  26946. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26947. return this;
  26948. }
  26949. // Alpha mode
  26950. if (enableAlphaMode) {
  26951. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26952. }
  26953. // Outline - step 1
  26954. var savedDepthWrite = engine.getDepthWrite();
  26955. if (this.renderOutline) {
  26956. engine.setDepthWrite(false);
  26957. scene.getOutlineRenderer().render(subMesh, batch);
  26958. engine.setDepthWrite(savedDepthWrite);
  26959. }
  26960. var effect;
  26961. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26962. effect = subMesh.effect;
  26963. }
  26964. else {
  26965. effect = this._effectiveMaterial.getEffect();
  26966. }
  26967. if (!effect) {
  26968. return this;
  26969. }
  26970. var sideOrientation = this.overrideMaterialSideOrientation;
  26971. if (sideOrientation == null) {
  26972. sideOrientation = this._effectiveMaterial.sideOrientation;
  26973. if (this._getWorldMatrixDeterminant() < 0) {
  26974. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26975. }
  26976. }
  26977. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26978. if (this._effectiveMaterial.forceDepthWrite) {
  26979. engine.setDepthWrite(true);
  26980. }
  26981. // Bind
  26982. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26983. if (!hardwareInstancedRendering) {
  26984. this._bind(subMesh, effect, fillMode);
  26985. }
  26986. var world = this.getWorldMatrix();
  26987. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26988. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26989. }
  26990. else {
  26991. this._effectiveMaterial.bind(world, this);
  26992. }
  26993. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26994. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26995. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26996. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26997. }
  26998. // Draw
  26999. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27000. // Unbind
  27001. this._effectiveMaterial.unbind();
  27002. // Outline - step 2
  27003. if (this.renderOutline && savedDepthWrite) {
  27004. engine.setDepthWrite(true);
  27005. engine.setColorWrite(false);
  27006. scene.getOutlineRenderer().render(subMesh, batch);
  27007. engine.setColorWrite(true);
  27008. }
  27009. // Overlay
  27010. if (this.renderOverlay) {
  27011. var currentMode = engine.getAlphaMode();
  27012. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27013. scene.getOutlineRenderer().render(subMesh, batch, true);
  27014. engine.setAlphaMode(currentMode);
  27015. }
  27016. this.onAfterRenderObservable.notifyObservers(this);
  27017. return this;
  27018. };
  27019. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27020. if (isInstance && effectiveMaterial) {
  27021. effectiveMaterial.bindOnlyWorldMatrix(world);
  27022. }
  27023. };
  27024. /**
  27025. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27026. */
  27027. Mesh.prototype.getEmittedParticleSystems = function () {
  27028. var results = new Array();
  27029. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27030. var particleSystem = this.getScene().particleSystems[index];
  27031. if (particleSystem.emitter === this) {
  27032. results.push(particleSystem);
  27033. }
  27034. }
  27035. return results;
  27036. };
  27037. /**
  27038. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27039. */
  27040. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27041. var results = new Array();
  27042. var descendants = this.getDescendants();
  27043. descendants.push(this);
  27044. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27045. var particleSystem = this.getScene().particleSystems[index];
  27046. var emitter = particleSystem.emitter;
  27047. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27048. results.push(particleSystem);
  27049. }
  27050. }
  27051. return results;
  27052. };
  27053. Mesh.prototype._checkDelayState = function () {
  27054. var scene = this.getScene();
  27055. if (this._geometry) {
  27056. this._geometry.load(scene);
  27057. }
  27058. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27059. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27060. this._queueLoad(scene);
  27061. }
  27062. return this;
  27063. };
  27064. Mesh.prototype._queueLoad = function (scene) {
  27065. var _this = this;
  27066. scene._addPendingData(this);
  27067. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27068. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27069. if (data instanceof ArrayBuffer) {
  27070. _this._delayLoadingFunction(data, _this);
  27071. }
  27072. else {
  27073. _this._delayLoadingFunction(JSON.parse(data), _this);
  27074. }
  27075. _this.instances.forEach(function (instance) {
  27076. instance._syncSubMeshes();
  27077. });
  27078. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27079. scene._removePendingData(_this);
  27080. }, function () { }, scene.database, getBinaryData);
  27081. return this;
  27082. };
  27083. /**
  27084. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27085. */
  27086. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27087. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27088. return false;
  27089. }
  27090. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27091. return false;
  27092. }
  27093. this._checkDelayState();
  27094. return true;
  27095. };
  27096. /**
  27097. * Sets the mesh material by the material or multiMaterial `id` property.
  27098. * The material `id` is a string identifying the material or the multiMaterial.
  27099. * This method returns the Mesh.
  27100. */
  27101. Mesh.prototype.setMaterialByID = function (id) {
  27102. var materials = this.getScene().materials;
  27103. var index;
  27104. for (index = materials.length - 1; index > -1; index--) {
  27105. if (materials[index].id === id) {
  27106. this.material = materials[index];
  27107. return this;
  27108. }
  27109. }
  27110. // Multi
  27111. var multiMaterials = this.getScene().multiMaterials;
  27112. for (index = multiMaterials.length - 1; index > -1; index--) {
  27113. if (multiMaterials[index].id === id) {
  27114. this.material = multiMaterials[index];
  27115. return this;
  27116. }
  27117. }
  27118. return this;
  27119. };
  27120. /**
  27121. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27122. */
  27123. Mesh.prototype.getAnimatables = function () {
  27124. var results = new Array();
  27125. if (this.material) {
  27126. results.push(this.material);
  27127. }
  27128. if (this.skeleton) {
  27129. results.push(this.skeleton);
  27130. }
  27131. return results;
  27132. };
  27133. /**
  27134. * Modifies the mesh geometry according to the passed transformation matrix.
  27135. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27136. * The mesh normals are modified accordingly the same transformation.
  27137. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27138. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27139. * Returns the Mesh.
  27140. */
  27141. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27142. // Position
  27143. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27144. return this;
  27145. }
  27146. var submeshes = this.subMeshes.splice(0);
  27147. this._resetPointsArrayCache();
  27148. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27149. var temp = new Array();
  27150. var index;
  27151. for (index = 0; index < data.length; index += 3) {
  27152. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27153. }
  27154. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27155. // Normals
  27156. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27157. return this;
  27158. }
  27159. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27160. temp = [];
  27161. for (index = 0; index < data.length; index += 3) {
  27162. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27163. }
  27164. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27165. // flip faces?
  27166. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27167. this.flipFaces();
  27168. }
  27169. // Restore submeshes
  27170. this.releaseSubMeshes();
  27171. this.subMeshes = submeshes;
  27172. return this;
  27173. };
  27174. /**
  27175. * Modifies the mesh geometry according to its own current World Matrix.
  27176. * The mesh World Matrix is then reset.
  27177. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27178. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27179. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27180. * Returns the Mesh.
  27181. */
  27182. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27183. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27184. this.scaling.copyFromFloats(1, 1, 1);
  27185. this.position.copyFromFloats(0, 0, 0);
  27186. this.rotation.copyFromFloats(0, 0, 0);
  27187. //only if quaternion is already set
  27188. if (this.rotationQuaternion) {
  27189. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27190. }
  27191. this._worldMatrix = BABYLON.Matrix.Identity();
  27192. return this;
  27193. };
  27194. Object.defineProperty(Mesh.prototype, "_positions", {
  27195. // Cache
  27196. get: function () {
  27197. if (this._geometry) {
  27198. return this._geometry._positions;
  27199. }
  27200. return null;
  27201. },
  27202. enumerable: true,
  27203. configurable: true
  27204. });
  27205. Mesh.prototype._resetPointsArrayCache = function () {
  27206. if (this._geometry) {
  27207. this._geometry._resetPointsArrayCache();
  27208. }
  27209. return this;
  27210. };
  27211. Mesh.prototype._generatePointsArray = function () {
  27212. if (this._geometry) {
  27213. return this._geometry._generatePointsArray();
  27214. }
  27215. return false;
  27216. };
  27217. /**
  27218. * Returns a new Mesh object generated from the current mesh properties.
  27219. * This method must not get confused with createInstance().
  27220. * The parameter `name` is a string, the name given to the new mesh.
  27221. * The optional parameter `newParent` can be any Node object (default `null`).
  27222. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27223. * 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.
  27224. */
  27225. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27226. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27227. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27228. };
  27229. /**
  27230. * Disposes the Mesh.
  27231. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27232. * Returns nothing.
  27233. */
  27234. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27235. var _this = this;
  27236. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27237. this.morphTargetManager = null;
  27238. if (this._geometry) {
  27239. this._geometry.releaseForMesh(this, true);
  27240. }
  27241. // Sources
  27242. var meshes = this.getScene().meshes;
  27243. meshes.forEach(function (abstractMesh) {
  27244. var mesh = abstractMesh;
  27245. if (mesh._source && mesh._source === _this) {
  27246. mesh._source = null;
  27247. }
  27248. });
  27249. this._source = null;
  27250. // Instances
  27251. if (this._instancesBuffer) {
  27252. this._instancesBuffer.dispose();
  27253. this._instancesBuffer = null;
  27254. }
  27255. while (this.instances.length) {
  27256. this.instances[0].dispose();
  27257. }
  27258. // Highlight layers.
  27259. var highlightLayers = this.getScene().highlightLayers;
  27260. for (var i = 0; i < highlightLayers.length; i++) {
  27261. var highlightLayer = highlightLayers[i];
  27262. if (highlightLayer) {
  27263. highlightLayer.removeMesh(this);
  27264. highlightLayer.removeExcludedMesh(this);
  27265. }
  27266. }
  27267. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27268. };
  27269. /**
  27270. * Modifies the mesh geometry according to a displacement map.
  27271. * 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.
  27272. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27273. * This method returns nothing.
  27274. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27275. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27276. * 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.
  27277. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27278. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27279. *
  27280. * Returns the Mesh.
  27281. */
  27282. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27283. var _this = this;
  27284. var scene = this.getScene();
  27285. var onload = function (img) {
  27286. // Getting height map data
  27287. var canvas = document.createElement("canvas");
  27288. var context = canvas.getContext("2d");
  27289. var heightMapWidth = img.width;
  27290. var heightMapHeight = img.height;
  27291. canvas.width = heightMapWidth;
  27292. canvas.height = heightMapHeight;
  27293. context.drawImage(img, 0, 0);
  27294. // Create VertexData from map data
  27295. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27296. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27297. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27298. //execute success callback, if set
  27299. if (onSuccess) {
  27300. onSuccess(_this);
  27301. }
  27302. };
  27303. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27304. return this;
  27305. };
  27306. /**
  27307. * Modifies the mesh geometry according to a displacementMap buffer.
  27308. * 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.
  27309. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27310. * This method returns nothing.
  27311. * 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.
  27312. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27313. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27314. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27315. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27316. *
  27317. * Returns the Mesh.
  27318. */
  27319. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27320. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27321. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27322. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27323. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27324. return this;
  27325. }
  27326. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27327. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27328. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27329. var position = BABYLON.Vector3.Zero();
  27330. var normal = BABYLON.Vector3.Zero();
  27331. var uv = BABYLON.Vector2.Zero();
  27332. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27333. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27334. for (var index = 0; index < positions.length; index += 3) {
  27335. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27336. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27337. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27338. // Compute height
  27339. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27340. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27341. var pos = (u + v * heightMapWidth) * 4;
  27342. var r = buffer[pos] / 255.0;
  27343. var g = buffer[pos + 1] / 255.0;
  27344. var b = buffer[pos + 2] / 255.0;
  27345. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27346. normal.normalize();
  27347. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27348. position = position.add(normal);
  27349. position.toArray(positions, index);
  27350. }
  27351. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27352. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27353. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27354. return this;
  27355. };
  27356. /**
  27357. * Modify the mesh to get a flat shading rendering.
  27358. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27359. * This method returns the Mesh.
  27360. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27361. */
  27362. Mesh.prototype.convertToFlatShadedMesh = function () {
  27363. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27364. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27365. var kinds = this.getVerticesDataKinds();
  27366. var vbs = {};
  27367. var data = {};
  27368. var newdata = {};
  27369. var updatableNormals = false;
  27370. var kindIndex;
  27371. var kind;
  27372. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27373. kind = kinds[kindIndex];
  27374. var vertexBuffer = this.getVertexBuffer(kind);
  27375. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27376. updatableNormals = vertexBuffer.isUpdatable();
  27377. kinds.splice(kindIndex, 1);
  27378. kindIndex--;
  27379. continue;
  27380. }
  27381. vbs[kind] = vertexBuffer;
  27382. data[kind] = vbs[kind].getData();
  27383. newdata[kind] = [];
  27384. }
  27385. // Save previous submeshes
  27386. var previousSubmeshes = this.subMeshes.slice(0);
  27387. var indices = this.getIndices();
  27388. var totalIndices = this.getTotalIndices();
  27389. // Generating unique vertices per face
  27390. var index;
  27391. for (index = 0; index < totalIndices; index++) {
  27392. var vertexIndex = indices[index];
  27393. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27394. kind = kinds[kindIndex];
  27395. var stride = vbs[kind].getStrideSize();
  27396. for (var offset = 0; offset < stride; offset++) {
  27397. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27398. }
  27399. }
  27400. }
  27401. // Updating faces & normal
  27402. var normals = [];
  27403. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27404. for (index = 0; index < totalIndices; index += 3) {
  27405. indices[index] = index;
  27406. indices[index + 1] = index + 1;
  27407. indices[index + 2] = index + 2;
  27408. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27409. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27410. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27411. var p1p2 = p1.subtract(p2);
  27412. var p3p2 = p3.subtract(p2);
  27413. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27414. // Store same normals for every vertex
  27415. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27416. normals.push(normal.x);
  27417. normals.push(normal.y);
  27418. normals.push(normal.z);
  27419. }
  27420. }
  27421. this.setIndices(indices);
  27422. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27423. // Updating vertex buffers
  27424. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27425. kind = kinds[kindIndex];
  27426. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27427. }
  27428. // Updating submeshes
  27429. this.releaseSubMeshes();
  27430. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27431. var previousOne = previousSubmeshes[submeshIndex];
  27432. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27433. }
  27434. this.synchronizeInstances();
  27435. return this;
  27436. };
  27437. /**
  27438. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27439. * In other words, more vertices, no more indices and a single bigger VBO.
  27440. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27441. * Returns the Mesh.
  27442. */
  27443. Mesh.prototype.convertToUnIndexedMesh = function () {
  27444. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27445. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27446. var kinds = this.getVerticesDataKinds();
  27447. var vbs = {};
  27448. var data = {};
  27449. var newdata = {};
  27450. var kindIndex;
  27451. var kind;
  27452. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27453. kind = kinds[kindIndex];
  27454. var vertexBuffer = this.getVertexBuffer(kind);
  27455. vbs[kind] = vertexBuffer;
  27456. data[kind] = vbs[kind].getData();
  27457. newdata[kind] = [];
  27458. }
  27459. // Save previous submeshes
  27460. var previousSubmeshes = this.subMeshes.slice(0);
  27461. var indices = this.getIndices();
  27462. var totalIndices = this.getTotalIndices();
  27463. // Generating unique vertices per face
  27464. var index;
  27465. for (index = 0; index < totalIndices; index++) {
  27466. var vertexIndex = indices[index];
  27467. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27468. kind = kinds[kindIndex];
  27469. var stride = vbs[kind].getStrideSize();
  27470. for (var offset = 0; offset < stride; offset++) {
  27471. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27472. }
  27473. }
  27474. }
  27475. // Updating indices
  27476. for (index = 0; index < totalIndices; index += 3) {
  27477. indices[index] = index;
  27478. indices[index + 1] = index + 1;
  27479. indices[index + 2] = index + 2;
  27480. }
  27481. this.setIndices(indices);
  27482. // Updating vertex buffers
  27483. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27484. kind = kinds[kindIndex];
  27485. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27486. }
  27487. // Updating submeshes
  27488. this.releaseSubMeshes();
  27489. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27490. var previousOne = previousSubmeshes[submeshIndex];
  27491. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27492. }
  27493. this._unIndexed = true;
  27494. this.synchronizeInstances();
  27495. return this;
  27496. };
  27497. /**
  27498. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27499. * This method returns the Mesh.
  27500. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27501. */
  27502. Mesh.prototype.flipFaces = function (flipNormals) {
  27503. if (flipNormals === void 0) { flipNormals = false; }
  27504. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27505. var i;
  27506. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27507. for (i = 0; i < vertex_data.normals.length; i++) {
  27508. vertex_data.normals[i] *= -1;
  27509. }
  27510. }
  27511. if (vertex_data.indices) {
  27512. var temp;
  27513. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27514. // reassign indices
  27515. temp = vertex_data.indices[i + 1];
  27516. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27517. vertex_data.indices[i + 2] = temp;
  27518. }
  27519. }
  27520. vertex_data.applyToMesh(this);
  27521. return this;
  27522. };
  27523. // Instances
  27524. /**
  27525. * Creates a new InstancedMesh object from the mesh model.
  27526. * An instance shares the same properties and the same material than its model.
  27527. * Only these properties of each instance can then be set individually :
  27528. * - position
  27529. * - rotation
  27530. * - rotationQuaternion
  27531. * - setPivotMatrix
  27532. * - scaling
  27533. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27534. * Warning : this method is not supported for Line mesh and LineSystem
  27535. */
  27536. Mesh.prototype.createInstance = function (name) {
  27537. return new BABYLON.InstancedMesh(name, this);
  27538. };
  27539. /**
  27540. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27541. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27542. * This method returns the Mesh.
  27543. */
  27544. Mesh.prototype.synchronizeInstances = function () {
  27545. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27546. var instance = this.instances[instanceIndex];
  27547. instance._syncSubMeshes();
  27548. }
  27549. return this;
  27550. };
  27551. /**
  27552. * Simplify the mesh according to the given array of settings.
  27553. * Function will return immediately and will simplify async. It returns the Mesh.
  27554. * @param settings a collection of simplification settings.
  27555. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27556. * @param type the type of simplification to run.
  27557. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27558. */
  27559. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27560. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27561. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27562. this.getScene().simplificationQueue.addTask({
  27563. settings: settings,
  27564. parallelProcessing: parallelProcessing,
  27565. mesh: this,
  27566. simplificationType: simplificationType,
  27567. successCallback: successCallback
  27568. });
  27569. return this;
  27570. };
  27571. /**
  27572. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27573. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27574. * This should be used together with the simplification to avoid disappearing triangles.
  27575. * Returns the Mesh.
  27576. * @param successCallback an optional success callback to be called after the optimization finished.
  27577. */
  27578. Mesh.prototype.optimizeIndices = function (successCallback) {
  27579. var _this = this;
  27580. var indices = this.getIndices();
  27581. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27582. if (!positions || !indices) {
  27583. return this;
  27584. }
  27585. var vectorPositions = new Array();
  27586. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27587. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27588. }
  27589. var dupes = new Array();
  27590. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27591. var realPos = vectorPositions.length - 1 - iteration;
  27592. var testedPosition = vectorPositions[realPos];
  27593. for (var j = 0; j < realPos; ++j) {
  27594. var againstPosition = vectorPositions[j];
  27595. if (testedPosition.equals(againstPosition)) {
  27596. dupes[realPos] = j;
  27597. break;
  27598. }
  27599. }
  27600. }, function () {
  27601. for (var i = 0; i < indices.length; ++i) {
  27602. indices[i] = dupes[indices[i]] || indices[i];
  27603. }
  27604. //indices are now reordered
  27605. var originalSubMeshes = _this.subMeshes.slice(0);
  27606. _this.setIndices(indices);
  27607. _this.subMeshes = originalSubMeshes;
  27608. if (successCallback) {
  27609. successCallback(_this);
  27610. }
  27611. });
  27612. return this;
  27613. };
  27614. Mesh.prototype.serialize = function (serializationObject) {
  27615. serializationObject.name = this.name;
  27616. serializationObject.id = this.id;
  27617. serializationObject.type = this.getClassName();
  27618. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27619. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27620. }
  27621. serializationObject.position = this.position.asArray();
  27622. if (this.rotationQuaternion) {
  27623. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27624. }
  27625. else if (this.rotation) {
  27626. serializationObject.rotation = this.rotation.asArray();
  27627. }
  27628. serializationObject.scaling = this.scaling.asArray();
  27629. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27630. serializationObject.isEnabled = this.isEnabled(false);
  27631. serializationObject.isVisible = this.isVisible;
  27632. serializationObject.infiniteDistance = this.infiniteDistance;
  27633. serializationObject.pickable = this.isPickable;
  27634. serializationObject.receiveShadows = this.receiveShadows;
  27635. serializationObject.billboardMode = this.billboardMode;
  27636. serializationObject.visibility = this.visibility;
  27637. serializationObject.checkCollisions = this.checkCollisions;
  27638. serializationObject.isBlocker = this.isBlocker;
  27639. // Parent
  27640. if (this.parent) {
  27641. serializationObject.parentId = this.parent.id;
  27642. }
  27643. // Geometry
  27644. serializationObject.isUnIndexed = this.isUnIndexed;
  27645. var geometry = this._geometry;
  27646. if (geometry) {
  27647. var geometryId = geometry.id;
  27648. serializationObject.geometryId = geometryId;
  27649. // SubMeshes
  27650. serializationObject.subMeshes = [];
  27651. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27652. var subMesh = this.subMeshes[subIndex];
  27653. serializationObject.subMeshes.push({
  27654. materialIndex: subMesh.materialIndex,
  27655. verticesStart: subMesh.verticesStart,
  27656. verticesCount: subMesh.verticesCount,
  27657. indexStart: subMesh.indexStart,
  27658. indexCount: subMesh.indexCount
  27659. });
  27660. }
  27661. }
  27662. // Material
  27663. if (this.material) {
  27664. serializationObject.materialId = this.material.id;
  27665. }
  27666. else {
  27667. this.material = null;
  27668. }
  27669. // Morph targets
  27670. if (this.morphTargetManager) {
  27671. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27672. }
  27673. // Skeleton
  27674. if (this.skeleton) {
  27675. serializationObject.skeletonId = this.skeleton.id;
  27676. }
  27677. // Physics
  27678. //TODO implement correct serialization for physics impostors.
  27679. var impostor = this.getPhysicsImpostor();
  27680. if (impostor) {
  27681. serializationObject.physicsMass = impostor.getParam("mass");
  27682. serializationObject.physicsFriction = impostor.getParam("friction");
  27683. serializationObject.physicsRestitution = impostor.getParam("mass");
  27684. serializationObject.physicsImpostor = impostor.type;
  27685. }
  27686. // Metadata
  27687. if (this.metadata) {
  27688. serializationObject.metadata = this.metadata;
  27689. }
  27690. // Instances
  27691. serializationObject.instances = [];
  27692. for (var index = 0; index < this.instances.length; index++) {
  27693. var instance = this.instances[index];
  27694. var serializationInstance = {
  27695. name: instance.name,
  27696. id: instance.id,
  27697. position: instance.position.asArray(),
  27698. scaling: instance.scaling.asArray()
  27699. };
  27700. if (instance.rotationQuaternion) {
  27701. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27702. }
  27703. else if (instance.rotation) {
  27704. serializationInstance.rotation = instance.rotation.asArray();
  27705. }
  27706. serializationObject.instances.push(serializationInstance);
  27707. // Animations
  27708. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27709. serializationInstance.ranges = instance.serializeAnimationRanges();
  27710. }
  27711. //
  27712. // Animations
  27713. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27714. serializationObject.ranges = this.serializeAnimationRanges();
  27715. // Layer mask
  27716. serializationObject.layerMask = this.layerMask;
  27717. // Alpha
  27718. serializationObject.alphaIndex = this.alphaIndex;
  27719. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27720. // Overlay
  27721. serializationObject.overlayAlpha = this.overlayAlpha;
  27722. serializationObject.overlayColor = this.overlayColor.asArray();
  27723. serializationObject.renderOverlay = this.renderOverlay;
  27724. // Fog
  27725. serializationObject.applyFog = this.applyFog;
  27726. // Action Manager
  27727. if (this.actionManager) {
  27728. serializationObject.actions = this.actionManager.serialize(this.name);
  27729. }
  27730. };
  27731. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27732. if (!this.geometry) {
  27733. return;
  27734. }
  27735. this._markSubMeshesAsAttributesDirty();
  27736. var morphTargetManager = this._morphTargetManager;
  27737. if (morphTargetManager && morphTargetManager.vertexCount) {
  27738. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27739. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27740. this.morphTargetManager = null;
  27741. return;
  27742. }
  27743. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27744. var morphTarget = morphTargetManager.getActiveTarget(index);
  27745. var positions = morphTarget.getPositions();
  27746. if (!positions) {
  27747. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27748. return;
  27749. }
  27750. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27751. var normals = morphTarget.getNormals();
  27752. if (normals) {
  27753. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27754. }
  27755. var tangents = morphTarget.getTangents();
  27756. if (tangents) {
  27757. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27758. }
  27759. }
  27760. }
  27761. else {
  27762. var index = 0;
  27763. // Positions
  27764. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27765. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27766. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27767. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27768. }
  27769. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27770. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27771. }
  27772. index++;
  27773. }
  27774. }
  27775. };
  27776. // Statics
  27777. /**
  27778. * Returns a new Mesh object parsed from the source provided.
  27779. * The parameter `parsedMesh` is the source.
  27780. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27781. */
  27782. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27783. var mesh;
  27784. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27785. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27786. }
  27787. else {
  27788. mesh = new Mesh(parsedMesh.name, scene);
  27789. }
  27790. mesh.id = parsedMesh.id;
  27791. if (BABYLON.Tags) {
  27792. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27793. }
  27794. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27795. if (parsedMesh.metadata !== undefined) {
  27796. mesh.metadata = parsedMesh.metadata;
  27797. }
  27798. if (parsedMesh.rotationQuaternion) {
  27799. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27800. }
  27801. else if (parsedMesh.rotation) {
  27802. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27803. }
  27804. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27805. if (parsedMesh.localMatrix) {
  27806. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27807. }
  27808. else if (parsedMesh.pivotMatrix) {
  27809. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27810. }
  27811. mesh.setEnabled(parsedMesh.isEnabled);
  27812. mesh.isVisible = parsedMesh.isVisible;
  27813. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27814. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27815. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27816. if (parsedMesh.applyFog !== undefined) {
  27817. mesh.applyFog = parsedMesh.applyFog;
  27818. }
  27819. if (parsedMesh.pickable !== undefined) {
  27820. mesh.isPickable = parsedMesh.pickable;
  27821. }
  27822. if (parsedMesh.alphaIndex !== undefined) {
  27823. mesh.alphaIndex = parsedMesh.alphaIndex;
  27824. }
  27825. mesh.receiveShadows = parsedMesh.receiveShadows;
  27826. mesh.billboardMode = parsedMesh.billboardMode;
  27827. if (parsedMesh.visibility !== undefined) {
  27828. mesh.visibility = parsedMesh.visibility;
  27829. }
  27830. mesh.checkCollisions = parsedMesh.checkCollisions;
  27831. if (parsedMesh.isBlocker !== undefined) {
  27832. mesh.isBlocker = parsedMesh.isBlocker;
  27833. }
  27834. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27835. // freezeWorldMatrix
  27836. if (parsedMesh.freezeWorldMatrix) {
  27837. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27838. }
  27839. // Parent
  27840. if (parsedMesh.parentId) {
  27841. mesh._waitingParentId = parsedMesh.parentId;
  27842. }
  27843. // Actions
  27844. if (parsedMesh.actions !== undefined) {
  27845. mesh._waitingActions = parsedMesh.actions;
  27846. }
  27847. // Overlay
  27848. if (parsedMesh.overlayAlpha !== undefined) {
  27849. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27850. }
  27851. if (parsedMesh.overlayColor !== undefined) {
  27852. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27853. }
  27854. if (parsedMesh.renderOverlay !== undefined) {
  27855. mesh.renderOverlay = parsedMesh.renderOverlay;
  27856. }
  27857. // Geometry
  27858. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27859. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27860. if (parsedMesh.delayLoadingFile) {
  27861. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27862. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27863. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27864. if (parsedMesh._binaryInfo) {
  27865. mesh._binaryInfo = parsedMesh._binaryInfo;
  27866. }
  27867. mesh._delayInfo = [];
  27868. if (parsedMesh.hasUVs) {
  27869. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27870. }
  27871. if (parsedMesh.hasUVs2) {
  27872. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27873. }
  27874. if (parsedMesh.hasUVs3) {
  27875. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27876. }
  27877. if (parsedMesh.hasUVs4) {
  27878. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27879. }
  27880. if (parsedMesh.hasUVs5) {
  27881. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27882. }
  27883. if (parsedMesh.hasUVs6) {
  27884. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27885. }
  27886. if (parsedMesh.hasColors) {
  27887. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27888. }
  27889. if (parsedMesh.hasMatricesIndices) {
  27890. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27891. }
  27892. if (parsedMesh.hasMatricesWeights) {
  27893. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27894. }
  27895. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27896. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27897. mesh._checkDelayState();
  27898. }
  27899. }
  27900. else {
  27901. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27902. }
  27903. // Material
  27904. if (parsedMesh.materialId) {
  27905. mesh.setMaterialByID(parsedMesh.materialId);
  27906. }
  27907. else {
  27908. mesh.material = null;
  27909. }
  27910. // Morph targets
  27911. if (parsedMesh.morphTargetManagerId > -1) {
  27912. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27913. }
  27914. // Skeleton
  27915. if (parsedMesh.skeletonId > -1) {
  27916. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27917. if (parsedMesh.numBoneInfluencers) {
  27918. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27919. }
  27920. }
  27921. // Animations
  27922. if (parsedMesh.animations) {
  27923. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27924. var parsedAnimation = parsedMesh.animations[animationIndex];
  27925. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27926. }
  27927. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27928. }
  27929. if (parsedMesh.autoAnimate) {
  27930. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27931. }
  27932. // Layer Mask
  27933. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27934. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27935. }
  27936. else {
  27937. mesh.layerMask = 0x0FFFFFFF;
  27938. }
  27939. // Physics
  27940. if (parsedMesh.physicsImpostor) {
  27941. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27942. mass: parsedMesh.physicsMass,
  27943. friction: parsedMesh.physicsFriction,
  27944. restitution: parsedMesh.physicsRestitution
  27945. }, scene);
  27946. }
  27947. // Instances
  27948. if (parsedMesh.instances) {
  27949. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27950. var parsedInstance = parsedMesh.instances[index];
  27951. var instance = mesh.createInstance(parsedInstance.name);
  27952. if (parsedInstance.id) {
  27953. instance.id = parsedInstance.id;
  27954. }
  27955. if (BABYLON.Tags) {
  27956. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27957. }
  27958. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27959. if (parsedInstance.parentId) {
  27960. instance._waitingParentId = parsedInstance.parentId;
  27961. }
  27962. if (parsedInstance.rotationQuaternion) {
  27963. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27964. }
  27965. else if (parsedInstance.rotation) {
  27966. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27967. }
  27968. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27969. instance.checkCollisions = mesh.checkCollisions;
  27970. if (parsedMesh.animations) {
  27971. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27972. parsedAnimation = parsedMesh.animations[animationIndex];
  27973. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27974. }
  27975. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27976. }
  27977. }
  27978. }
  27979. return mesh;
  27980. };
  27981. /**
  27982. * Creates a ribbon mesh.
  27983. * Please consider using the same method from the MeshBuilder class instead.
  27984. * 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.
  27985. *
  27986. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27987. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27988. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27989. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27990. * 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.
  27991. * 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.
  27992. * 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
  27993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27996. */
  27997. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27998. if (closeArray === void 0) { closeArray = false; }
  27999. if (updatable === void 0) { updatable = false; }
  28000. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28001. pathArray: pathArray,
  28002. closeArray: closeArray,
  28003. closePath: closePath,
  28004. offset: offset,
  28005. updatable: updatable,
  28006. sideOrientation: sideOrientation,
  28007. instance: instance
  28008. }, scene);
  28009. };
  28010. /**
  28011. * Creates a plane polygonal mesh. By default, this is a disc.
  28012. * Please consider using the same method from the MeshBuilder class instead.
  28013. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28014. * 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.
  28015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28018. */
  28019. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28020. if (scene === void 0) { scene = null; }
  28021. var options = {
  28022. radius: radius,
  28023. tessellation: tessellation,
  28024. sideOrientation: sideOrientation,
  28025. updatable: updatable
  28026. };
  28027. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28028. };
  28029. /**
  28030. * Creates a box mesh.
  28031. * Please consider using the same method from the MeshBuilder class instead.
  28032. * The parameter `size` sets the size (float) of each box side (default 1).
  28033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28034. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28036. */
  28037. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28038. if (scene === void 0) { scene = null; }
  28039. var options = {
  28040. size: size,
  28041. sideOrientation: sideOrientation,
  28042. updatable: updatable
  28043. };
  28044. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28045. };
  28046. /**
  28047. * Creates a sphere mesh.
  28048. * Please consider using the same method from the MeshBuilder class instead.
  28049. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28050. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28054. */
  28055. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28056. var options = {
  28057. segments: segments,
  28058. diameterX: diameter,
  28059. diameterY: diameter,
  28060. diameterZ: diameter,
  28061. sideOrientation: sideOrientation,
  28062. updatable: updatable
  28063. };
  28064. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28065. };
  28066. /**
  28067. * Creates a cylinder or a cone mesh.
  28068. * Please consider using the same method from the MeshBuilder class instead.
  28069. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28070. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28071. * 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.
  28072. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28073. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28074. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28077. */
  28078. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28079. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28080. if (scene !== undefined) {
  28081. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28082. updatable = scene;
  28083. }
  28084. scene = subdivisions;
  28085. subdivisions = 1;
  28086. }
  28087. var options = {
  28088. height: height,
  28089. diameterTop: diameterTop,
  28090. diameterBottom: diameterBottom,
  28091. tessellation: tessellation,
  28092. subdivisions: subdivisions,
  28093. sideOrientation: sideOrientation,
  28094. updatable: updatable
  28095. };
  28096. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28097. };
  28098. // Torus (Code from SharpDX.org)
  28099. /**
  28100. * Creates a torus mesh.
  28101. * Please consider using the same method from the MeshBuilder class instead.
  28102. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28103. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28104. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28108. */
  28109. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28110. var options = {
  28111. diameter: diameter,
  28112. thickness: thickness,
  28113. tessellation: tessellation,
  28114. sideOrientation: sideOrientation,
  28115. updatable: updatable
  28116. };
  28117. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28118. };
  28119. /**
  28120. * Creates a torus knot mesh.
  28121. * Please consider using the same method from the MeshBuilder class instead.
  28122. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28123. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28124. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28125. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28129. */
  28130. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28131. var options = {
  28132. radius: radius,
  28133. tube: tube,
  28134. radialSegments: radialSegments,
  28135. tubularSegments: tubularSegments,
  28136. p: p,
  28137. q: q,
  28138. sideOrientation: sideOrientation,
  28139. updatable: updatable
  28140. };
  28141. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28142. };
  28143. /**
  28144. * Creates a line mesh.
  28145. * Please consider using the same method from the MeshBuilder class instead.
  28146. * 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.
  28147. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28148. * The parameter `points` is an array successive Vector3.
  28149. * 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
  28150. * When updating an instance, remember that only point positions can change, not the number of points.
  28151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28152. */
  28153. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28154. if (scene === void 0) { scene = null; }
  28155. if (updatable === void 0) { updatable = false; }
  28156. if (instance === void 0) { instance = null; }
  28157. var options = {
  28158. points: points,
  28159. updatable: updatable,
  28160. instance: instance
  28161. };
  28162. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28163. };
  28164. /**
  28165. * Creates a dashed line mesh.
  28166. * Please consider using the same method from the MeshBuilder class instead.
  28167. * 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.
  28168. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28169. * The parameter `points` is an array successive Vector3.
  28170. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28171. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28172. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28173. * 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
  28174. * When updating an instance, remember that only point positions can change, not the number of points.
  28175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28176. */
  28177. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28178. if (scene === void 0) { scene = null; }
  28179. var options = {
  28180. points: points,
  28181. dashSize: dashSize,
  28182. gapSize: gapSize,
  28183. dashNb: dashNb,
  28184. updatable: updatable,
  28185. instance: instance
  28186. };
  28187. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28188. };
  28189. /**
  28190. * Creates a polygon mesh.
  28191. * Please consider using the same method from the MeshBuilder class instead.
  28192. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28193. * 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.
  28194. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28196. * Remember you can only change the shape positions, not their number when updating a polygon.
  28197. */
  28198. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28199. var options = {
  28200. shape: shape,
  28201. holes: holes,
  28202. updatable: updatable,
  28203. sideOrientation: sideOrientation
  28204. };
  28205. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28206. };
  28207. /**
  28208. * Creates an extruded polygon mesh, with depth in the Y direction.
  28209. * Please consider using the same method from the MeshBuilder class instead.
  28210. */
  28211. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28212. var options = {
  28213. shape: shape,
  28214. holes: holes,
  28215. depth: depth,
  28216. updatable: updatable,
  28217. sideOrientation: sideOrientation
  28218. };
  28219. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28220. };
  28221. /**
  28222. * Creates an extruded shape mesh.
  28223. * 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.
  28224. * Please consider using the same method from the MeshBuilder class instead.
  28225. *
  28226. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28227. * 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
  28228. * extruded along the Z axis.
  28229. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28230. * 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.
  28231. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28232. * 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
  28233. * 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
  28234. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28236. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28238. */
  28239. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28240. if (scene === void 0) { scene = null; }
  28241. var options = {
  28242. shape: shape,
  28243. path: path,
  28244. scale: scale,
  28245. rotation: rotation,
  28246. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28247. sideOrientation: sideOrientation,
  28248. instance: instance,
  28249. updatable: updatable
  28250. };
  28251. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28252. };
  28253. /**
  28254. * Creates an custom extruded shape mesh.
  28255. * 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.
  28256. * Please consider using the same method from the MeshBuilder class instead.
  28257. *
  28258. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28259. * 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
  28260. * extruded along the Z axis.
  28261. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28262. * 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
  28263. * and the distance of this point from the begining of the path :
  28264. * ```javascript
  28265. * var rotationFunction = function(i, distance) {
  28266. * // do things
  28267. * return rotationValue; }
  28268. * ```
  28269. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28270. * 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
  28271. * and the distance of this point from the begining of the path :
  28272. * ```javascript
  28273. * var scaleFunction = function(i, distance) {
  28274. * // do things
  28275. * return scaleValue;}
  28276. * ```
  28277. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28278. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28279. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28280. * 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
  28281. * 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
  28282. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28286. */
  28287. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28288. var options = {
  28289. shape: shape,
  28290. path: path,
  28291. scaleFunction: scaleFunction,
  28292. rotationFunction: rotationFunction,
  28293. ribbonCloseArray: ribbonCloseArray,
  28294. ribbonClosePath: ribbonClosePath,
  28295. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28296. sideOrientation: sideOrientation,
  28297. instance: instance,
  28298. updatable: updatable
  28299. };
  28300. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28301. };
  28302. /**
  28303. * Creates lathe mesh.
  28304. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28305. * Please consider using the same method from the MeshBuilder class instead.
  28306. * 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
  28307. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28308. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28309. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28311. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28313. */
  28314. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28315. var options = {
  28316. shape: shape,
  28317. radius: radius,
  28318. tessellation: tessellation,
  28319. sideOrientation: sideOrientation,
  28320. updatable: updatable
  28321. };
  28322. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28323. };
  28324. /**
  28325. * Creates a plane mesh.
  28326. * Please consider using the same method from the MeshBuilder class instead.
  28327. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28331. */
  28332. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28333. var options = {
  28334. size: size,
  28335. width: size,
  28336. height: size,
  28337. sideOrientation: sideOrientation,
  28338. updatable: updatable
  28339. };
  28340. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28341. };
  28342. /**
  28343. * Creates a ground mesh.
  28344. * Please consider using the same method from the MeshBuilder class instead.
  28345. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28346. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28348. */
  28349. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28350. var options = {
  28351. width: width,
  28352. height: height,
  28353. subdivisions: subdivisions,
  28354. updatable: updatable
  28355. };
  28356. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28357. };
  28358. /**
  28359. * Creates a tiled ground mesh.
  28360. * Please consider using the same method from the MeshBuilder class instead.
  28361. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28362. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28363. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28364. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28365. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28366. * numbers of subdivisions on the ground width and height of each tile.
  28367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28368. */
  28369. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28370. var options = {
  28371. xmin: xmin,
  28372. zmin: zmin,
  28373. xmax: xmax,
  28374. zmax: zmax,
  28375. subdivisions: subdivisions,
  28376. precision: precision,
  28377. updatable: updatable
  28378. };
  28379. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28380. };
  28381. /**
  28382. * Creates a ground mesh from a height map.
  28383. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28384. * Please consider using the same method from the MeshBuilder class instead.
  28385. * The parameter `url` sets the URL of the height map image resource.
  28386. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28387. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28388. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28389. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28390. * 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).
  28391. * This function is passed the newly built mesh :
  28392. * ```javascript
  28393. * function(mesh) { // do things
  28394. * return; }
  28395. * ```
  28396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28397. */
  28398. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28399. var options = {
  28400. width: width,
  28401. height: height,
  28402. subdivisions: subdivisions,
  28403. minHeight: minHeight,
  28404. maxHeight: maxHeight,
  28405. updatable: updatable,
  28406. onReady: onReady
  28407. };
  28408. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28409. };
  28410. /**
  28411. * Creates a tube mesh.
  28412. * 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.
  28413. * Please consider using the same method from the MeshBuilder class instead.
  28414. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28415. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28416. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28417. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28418. * 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.
  28419. * It must return a radius value (positive float) :
  28420. * ```javascript
  28421. * var radiusFunction = function(i, distance) {
  28422. * // do things
  28423. * return radius; }
  28424. * ```
  28425. * 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
  28426. * 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
  28427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28430. */
  28431. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28432. var options = {
  28433. path: path,
  28434. radius: radius,
  28435. tessellation: tessellation,
  28436. radiusFunction: radiusFunction,
  28437. arc: 1,
  28438. cap: cap,
  28439. updatable: updatable,
  28440. sideOrientation: sideOrientation,
  28441. instance: instance
  28442. };
  28443. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28444. };
  28445. /**
  28446. * Creates a polyhedron mesh.
  28447. * Please consider using the same method from the MeshBuilder class instead.
  28448. * 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
  28449. * to choose the wanted type.
  28450. * The parameter `size` (positive float, default 1) sets the polygon size.
  28451. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28452. * 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`.
  28453. * 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
  28454. * 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)`).
  28455. * 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
  28456. * 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.
  28457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28458. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28460. */
  28461. Mesh.CreatePolyhedron = function (name, options, scene) {
  28462. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28463. };
  28464. /**
  28465. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28466. * Please consider using the same method from the MeshBuilder class instead.
  28467. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28468. * 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`).
  28469. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28470. * 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.
  28471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28474. */
  28475. Mesh.CreateIcoSphere = function (name, options, scene) {
  28476. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28477. };
  28478. /**
  28479. * Creates a decal mesh.
  28480. * Please consider using the same method from the MeshBuilder class instead.
  28481. * 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.
  28482. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28483. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28484. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28485. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28486. */
  28487. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28488. var options = {
  28489. position: position,
  28490. normal: normal,
  28491. size: size,
  28492. angle: angle
  28493. };
  28494. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28495. };
  28496. // Skeletons
  28497. /**
  28498. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28499. */
  28500. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28501. if (!this._sourcePositions) {
  28502. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28503. if (!source) {
  28504. return this._sourcePositions;
  28505. }
  28506. this._sourcePositions = new Float32Array(source);
  28507. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28508. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28509. }
  28510. }
  28511. return this._sourcePositions;
  28512. };
  28513. /**
  28514. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28515. */
  28516. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28517. if (!this._sourceNormals) {
  28518. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28519. if (!source) {
  28520. return this._sourceNormals;
  28521. }
  28522. this._sourceNormals = new Float32Array(source);
  28523. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28524. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28525. }
  28526. }
  28527. return this._sourceNormals;
  28528. };
  28529. /**
  28530. * Updates the vertex buffer by applying transformation from the bones.
  28531. * Returns the Mesh.
  28532. *
  28533. * @param {skeleton} skeleton to apply
  28534. */
  28535. Mesh.prototype.applySkeleton = function (skeleton) {
  28536. if (!this.geometry) {
  28537. return this;
  28538. }
  28539. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28540. return this;
  28541. }
  28542. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28543. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28544. return this;
  28545. }
  28546. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28547. return this;
  28548. }
  28549. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28550. return this;
  28551. }
  28552. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28553. return this;
  28554. }
  28555. if (!this._sourcePositions) {
  28556. var submeshes = this.subMeshes.slice();
  28557. this.setPositionsForCPUSkinning();
  28558. this.subMeshes = submeshes;
  28559. }
  28560. if (!this._sourceNormals) {
  28561. this.setNormalsForCPUSkinning();
  28562. }
  28563. // positionsData checks for not being Float32Array will only pass at most once
  28564. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28565. if (!positionsData) {
  28566. return this;
  28567. }
  28568. if (!(positionsData instanceof Float32Array)) {
  28569. positionsData = new Float32Array(positionsData);
  28570. }
  28571. // normalsData checks for not being Float32Array will only pass at most once
  28572. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28573. if (!normalsData) {
  28574. return this;
  28575. }
  28576. if (!(normalsData instanceof Float32Array)) {
  28577. normalsData = new Float32Array(normalsData);
  28578. }
  28579. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28580. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28581. if (!matricesWeightsData || !matricesIndicesData) {
  28582. return this;
  28583. }
  28584. var needExtras = this.numBoneInfluencers > 4;
  28585. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28586. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28587. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28588. var tempVector3 = BABYLON.Vector3.Zero();
  28589. var finalMatrix = new BABYLON.Matrix();
  28590. var tempMatrix = new BABYLON.Matrix();
  28591. var matWeightIdx = 0;
  28592. var inf;
  28593. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28594. var weight;
  28595. for (inf = 0; inf < 4; inf++) {
  28596. weight = matricesWeightsData[matWeightIdx + inf];
  28597. if (weight > 0) {
  28598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28599. finalMatrix.addToSelf(tempMatrix);
  28600. }
  28601. else
  28602. break;
  28603. }
  28604. if (needExtras) {
  28605. for (inf = 0; inf < 4; inf++) {
  28606. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28607. if (weight > 0) {
  28608. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28609. finalMatrix.addToSelf(tempMatrix);
  28610. }
  28611. else
  28612. break;
  28613. }
  28614. }
  28615. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28616. tempVector3.toArray(positionsData, index);
  28617. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28618. tempVector3.toArray(normalsData, index);
  28619. finalMatrix.reset();
  28620. }
  28621. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28622. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28623. return this;
  28624. };
  28625. // Tools
  28626. /**
  28627. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28628. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28629. */
  28630. Mesh.MinMax = function (meshes) {
  28631. var minVector = null;
  28632. var maxVector = null;
  28633. meshes.forEach(function (mesh, index, array) {
  28634. var boundingInfo = mesh.getBoundingInfo();
  28635. var boundingBox = boundingInfo.boundingBox;
  28636. if (!minVector || !maxVector) {
  28637. minVector = boundingBox.minimumWorld;
  28638. maxVector = boundingBox.maximumWorld;
  28639. }
  28640. else {
  28641. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28642. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28643. }
  28644. });
  28645. if (!minVector || !maxVector) {
  28646. return {
  28647. min: BABYLON.Vector3.Zero(),
  28648. max: BABYLON.Vector3.Zero()
  28649. };
  28650. }
  28651. return {
  28652. min: minVector,
  28653. max: maxVector
  28654. };
  28655. };
  28656. /**
  28657. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28658. */
  28659. Mesh.Center = function (meshesOrMinMaxVector) {
  28660. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28661. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28662. };
  28663. /**
  28664. * Merge the array of meshes into a single mesh for performance reasons.
  28665. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28666. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28667. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28668. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28669. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28670. */
  28671. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28672. if (disposeSource === void 0) { disposeSource = true; }
  28673. var index;
  28674. if (!allow32BitsIndices) {
  28675. var totalVertices = 0;
  28676. // Counting vertices
  28677. for (index = 0; index < meshes.length; index++) {
  28678. if (meshes[index]) {
  28679. totalVertices += meshes[index].getTotalVertices();
  28680. if (totalVertices > 65536) {
  28681. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28682. return null;
  28683. }
  28684. }
  28685. }
  28686. }
  28687. // Merge
  28688. var vertexData = null;
  28689. var otherVertexData;
  28690. var indiceArray = new Array();
  28691. var source = null;
  28692. for (index = 0; index < meshes.length; index++) {
  28693. if (meshes[index]) {
  28694. meshes[index].computeWorldMatrix(true);
  28695. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28696. otherVertexData.transform(meshes[index].getWorldMatrix());
  28697. if (vertexData) {
  28698. vertexData.merge(otherVertexData);
  28699. }
  28700. else {
  28701. vertexData = otherVertexData;
  28702. source = meshes[index];
  28703. }
  28704. if (subdivideWithSubMeshes) {
  28705. indiceArray.push(meshes[index].getTotalIndices());
  28706. }
  28707. }
  28708. }
  28709. source = source;
  28710. if (!meshSubclass) {
  28711. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28712. }
  28713. vertexData.applyToMesh(meshSubclass);
  28714. // Setting properties
  28715. meshSubclass.material = source.material;
  28716. meshSubclass.checkCollisions = source.checkCollisions;
  28717. // Cleaning
  28718. if (disposeSource) {
  28719. for (index = 0; index < meshes.length; index++) {
  28720. if (meshes[index]) {
  28721. meshes[index].dispose();
  28722. }
  28723. }
  28724. }
  28725. // Subdivide
  28726. if (subdivideWithSubMeshes) {
  28727. //-- Suppresions du submesh global
  28728. meshSubclass.releaseSubMeshes();
  28729. index = 0;
  28730. var offset = 0;
  28731. //-- aplique la subdivision en fonction du tableau d'indices
  28732. while (index < indiceArray.length) {
  28733. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28734. offset += indiceArray[index];
  28735. index++;
  28736. }
  28737. }
  28738. return meshSubclass;
  28739. };
  28740. // Consts
  28741. Mesh._FRONTSIDE = 0;
  28742. Mesh._BACKSIDE = 1;
  28743. Mesh._DOUBLESIDE = 2;
  28744. Mesh._DEFAULTSIDE = 0;
  28745. Mesh._NO_CAP = 0;
  28746. Mesh._CAP_START = 1;
  28747. Mesh._CAP_END = 2;
  28748. Mesh._CAP_ALL = 3;
  28749. return Mesh;
  28750. }(BABYLON.AbstractMesh));
  28751. BABYLON.Mesh = Mesh;
  28752. })(BABYLON || (BABYLON = {}));
  28753. //# sourceMappingURL=babylon.mesh.js.map
  28754. var BABYLON;
  28755. (function (BABYLON) {
  28756. var BaseSubMesh = /** @class */ (function () {
  28757. function BaseSubMesh() {
  28758. }
  28759. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28760. get: function () {
  28761. return this._materialEffect;
  28762. },
  28763. enumerable: true,
  28764. configurable: true
  28765. });
  28766. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28767. if (defines === void 0) { defines = null; }
  28768. if (this._materialEffect === effect) {
  28769. if (!effect) {
  28770. this._materialDefines = null;
  28771. }
  28772. return;
  28773. }
  28774. this._materialDefines = defines;
  28775. this._materialEffect = effect;
  28776. };
  28777. return BaseSubMesh;
  28778. }());
  28779. BABYLON.BaseSubMesh = BaseSubMesh;
  28780. var SubMesh = /** @class */ (function (_super) {
  28781. __extends(SubMesh, _super);
  28782. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28783. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28784. var _this = _super.call(this) || this;
  28785. _this.materialIndex = materialIndex;
  28786. _this.verticesStart = verticesStart;
  28787. _this.verticesCount = verticesCount;
  28788. _this.indexStart = indexStart;
  28789. _this.indexCount = indexCount;
  28790. _this._renderId = 0;
  28791. _this._mesh = mesh;
  28792. _this._renderingMesh = renderingMesh || mesh;
  28793. mesh.subMeshes.push(_this);
  28794. _this._trianglePlanes = [];
  28795. _this._id = mesh.subMeshes.length - 1;
  28796. if (createBoundingBox) {
  28797. _this.refreshBoundingInfo();
  28798. mesh.computeWorldMatrix(true);
  28799. }
  28800. return _this;
  28801. }
  28802. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28803. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28804. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28805. };
  28806. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28807. get: function () {
  28808. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28809. },
  28810. enumerable: true,
  28811. configurable: true
  28812. });
  28813. /**
  28814. * Returns the submesh BoudingInfo object.
  28815. */
  28816. SubMesh.prototype.getBoundingInfo = function () {
  28817. if (this.IsGlobal) {
  28818. return this._mesh.getBoundingInfo();
  28819. }
  28820. return this._boundingInfo;
  28821. };
  28822. /**
  28823. * Sets the submesh BoundingInfo.
  28824. * Return the SubMesh.
  28825. */
  28826. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28827. this._boundingInfo = boundingInfo;
  28828. return this;
  28829. };
  28830. /**
  28831. * Returns the mesh of the current submesh.
  28832. */
  28833. SubMesh.prototype.getMesh = function () {
  28834. return this._mesh;
  28835. };
  28836. /**
  28837. * Returns the rendering mesh of the submesh.
  28838. */
  28839. SubMesh.prototype.getRenderingMesh = function () {
  28840. return this._renderingMesh;
  28841. };
  28842. /**
  28843. * Returns the submesh material.
  28844. */
  28845. SubMesh.prototype.getMaterial = function () {
  28846. var rootMaterial = this._renderingMesh.material;
  28847. if (rootMaterial === null || rootMaterial === undefined) {
  28848. return this._mesh.getScene().defaultMaterial;
  28849. }
  28850. else if (rootMaterial.getSubMaterial) {
  28851. var multiMaterial = rootMaterial;
  28852. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28853. if (this._currentMaterial !== effectiveMaterial) {
  28854. this._currentMaterial = effectiveMaterial;
  28855. this._materialDefines = null;
  28856. }
  28857. return effectiveMaterial;
  28858. }
  28859. return rootMaterial;
  28860. };
  28861. // Methods
  28862. /**
  28863. * Sets a new updated BoundingInfo object to the submesh.
  28864. * Returns the SubMesh.
  28865. */
  28866. SubMesh.prototype.refreshBoundingInfo = function () {
  28867. this._lastColliderWorldVertices = null;
  28868. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28869. return this;
  28870. }
  28871. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28872. if (!data) {
  28873. this._boundingInfo = this._mesh.getBoundingInfo();
  28874. return this;
  28875. }
  28876. var indices = this._renderingMesh.getIndices();
  28877. var extend;
  28878. //is this the only submesh?
  28879. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28880. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28881. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28882. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28883. }
  28884. else {
  28885. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28886. }
  28887. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28888. return this;
  28889. };
  28890. SubMesh.prototype._checkCollision = function (collider) {
  28891. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28892. return boundingInfo._checkCollision(collider);
  28893. };
  28894. /**
  28895. * Updates the submesh BoundingInfo.
  28896. * Returns the Submesh.
  28897. */
  28898. SubMesh.prototype.updateBoundingInfo = function (world) {
  28899. var boundingInfo = this.getBoundingInfo();
  28900. if (!boundingInfo) {
  28901. this.refreshBoundingInfo();
  28902. boundingInfo = this.getBoundingInfo();
  28903. }
  28904. boundingInfo.update(world);
  28905. return this;
  28906. };
  28907. /**
  28908. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28909. * Boolean returned.
  28910. */
  28911. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28912. var boundingInfo = this.getBoundingInfo();
  28913. if (!boundingInfo) {
  28914. return false;
  28915. }
  28916. return boundingInfo.isInFrustum(frustumPlanes);
  28917. };
  28918. /**
  28919. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28920. * Boolean returned.
  28921. */
  28922. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28923. var boundingInfo = this.getBoundingInfo();
  28924. if (!boundingInfo) {
  28925. return false;
  28926. }
  28927. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28928. };
  28929. /**
  28930. * Renders the submesh.
  28931. * Returns it.
  28932. */
  28933. SubMesh.prototype.render = function (enableAlphaMode) {
  28934. this._renderingMesh.render(this, enableAlphaMode);
  28935. return this;
  28936. };
  28937. /**
  28938. * Returns a new Index Buffer.
  28939. * Type returned : WebGLBuffer.
  28940. */
  28941. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28942. if (!this._linesIndexBuffer) {
  28943. var linesIndices = [];
  28944. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28945. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28946. }
  28947. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28948. this.linesIndexCount = linesIndices.length;
  28949. }
  28950. return this._linesIndexBuffer;
  28951. };
  28952. /**
  28953. * True is the passed Ray intersects the submesh bounding box.
  28954. * Boolean returned.
  28955. */
  28956. SubMesh.prototype.canIntersects = function (ray) {
  28957. var boundingInfo = this.getBoundingInfo();
  28958. if (!boundingInfo) {
  28959. return false;
  28960. }
  28961. return ray.intersectsBox(boundingInfo.boundingBox);
  28962. };
  28963. /**
  28964. * Returns an object IntersectionInfo.
  28965. */
  28966. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28967. var intersectInfo = null;
  28968. // LineMesh first as it's also a Mesh...
  28969. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28970. var lineMesh = this._mesh;
  28971. // Line test
  28972. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28973. var p0 = positions[indices[index]];
  28974. var p1 = positions[indices[index + 1]];
  28975. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28976. if (length < 0) {
  28977. continue;
  28978. }
  28979. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28980. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28981. if (fastCheck) {
  28982. break;
  28983. }
  28984. }
  28985. }
  28986. }
  28987. else {
  28988. // Triangles test
  28989. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28990. var p0 = positions[indices[index]];
  28991. var p1 = positions[indices[index + 1]];
  28992. var p2 = positions[indices[index + 2]];
  28993. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28994. if (currentIntersectInfo) {
  28995. if (currentIntersectInfo.distance < 0) {
  28996. continue;
  28997. }
  28998. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28999. intersectInfo = currentIntersectInfo;
  29000. intersectInfo.faceId = index / 3;
  29001. if (fastCheck) {
  29002. break;
  29003. }
  29004. }
  29005. }
  29006. }
  29007. }
  29008. return intersectInfo;
  29009. };
  29010. SubMesh.prototype._rebuild = function () {
  29011. if (this._linesIndexBuffer) {
  29012. this._linesIndexBuffer = null;
  29013. }
  29014. };
  29015. // Clone
  29016. /**
  29017. * Creates a new Submesh from the passed Mesh.
  29018. */
  29019. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29020. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29021. if (!this.IsGlobal) {
  29022. var boundingInfo = this.getBoundingInfo();
  29023. if (!boundingInfo) {
  29024. return result;
  29025. }
  29026. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29027. }
  29028. return result;
  29029. };
  29030. // Dispose
  29031. /**
  29032. * Disposes the Submesh.
  29033. * Returns nothing.
  29034. */
  29035. SubMesh.prototype.dispose = function () {
  29036. if (this._linesIndexBuffer) {
  29037. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29038. this._linesIndexBuffer = null;
  29039. }
  29040. // Remove from mesh
  29041. var index = this._mesh.subMeshes.indexOf(this);
  29042. this._mesh.subMeshes.splice(index, 1);
  29043. };
  29044. // Statics
  29045. /**
  29046. * Creates a new Submesh from the passed parameters :
  29047. * - materialIndex (integer) : the index of the main mesh material.
  29048. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29049. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29050. * - mesh (Mesh) : the main mesh to create the submesh from.
  29051. * - renderingMesh (optional Mesh) : rendering mesh.
  29052. */
  29053. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29054. var minVertexIndex = Number.MAX_VALUE;
  29055. var maxVertexIndex = -Number.MAX_VALUE;
  29056. renderingMesh = (renderingMesh || mesh);
  29057. var indices = renderingMesh.getIndices();
  29058. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29059. var vertexIndex = indices[index];
  29060. if (vertexIndex < minVertexIndex)
  29061. minVertexIndex = vertexIndex;
  29062. if (vertexIndex > maxVertexIndex)
  29063. maxVertexIndex = vertexIndex;
  29064. }
  29065. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29066. };
  29067. return SubMesh;
  29068. }(BaseSubMesh));
  29069. BABYLON.SubMesh = SubMesh;
  29070. })(BABYLON || (BABYLON = {}));
  29071. //# sourceMappingURL=babylon.subMesh.js.map
  29072. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29073. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29074. s = arguments[i];
  29075. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29076. t[p] = s[p];
  29077. }
  29078. return t;
  29079. };
  29080. var BABYLON;
  29081. (function (BABYLON) {
  29082. var MaterialDefines = /** @class */ (function () {
  29083. function MaterialDefines() {
  29084. this._isDirty = true;
  29085. this._areLightsDirty = true;
  29086. this._areAttributesDirty = true;
  29087. this._areTexturesDirty = true;
  29088. this._areFresnelDirty = true;
  29089. this._areMiscDirty = true;
  29090. this._areImageProcessingDirty = true;
  29091. this._normals = false;
  29092. this._uvs = false;
  29093. this._needNormals = false;
  29094. this._needUVs = false;
  29095. }
  29096. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29097. get: function () {
  29098. return this._isDirty;
  29099. },
  29100. enumerable: true,
  29101. configurable: true
  29102. });
  29103. MaterialDefines.prototype.markAsProcessed = function () {
  29104. this._isDirty = false;
  29105. this._areAttributesDirty = false;
  29106. this._areTexturesDirty = false;
  29107. this._areFresnelDirty = false;
  29108. this._areLightsDirty = false;
  29109. this._areMiscDirty = false;
  29110. this._areImageProcessingDirty = false;
  29111. };
  29112. MaterialDefines.prototype.markAsUnprocessed = function () {
  29113. this._isDirty = true;
  29114. };
  29115. MaterialDefines.prototype.markAllAsDirty = function () {
  29116. this._areTexturesDirty = true;
  29117. this._areAttributesDirty = true;
  29118. this._areLightsDirty = true;
  29119. this._areFresnelDirty = true;
  29120. this._areMiscDirty = true;
  29121. this._areImageProcessingDirty = true;
  29122. this._isDirty = true;
  29123. };
  29124. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29125. this._areImageProcessingDirty = true;
  29126. this._isDirty = true;
  29127. };
  29128. MaterialDefines.prototype.markAsLightDirty = function () {
  29129. this._areLightsDirty = true;
  29130. this._isDirty = true;
  29131. };
  29132. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29133. this._areAttributesDirty = true;
  29134. this._isDirty = true;
  29135. };
  29136. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29137. this._areTexturesDirty = true;
  29138. this._isDirty = true;
  29139. };
  29140. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29141. this._areFresnelDirty = true;
  29142. this._isDirty = true;
  29143. };
  29144. MaterialDefines.prototype.markAsMiscDirty = function () {
  29145. this._areMiscDirty = true;
  29146. this._isDirty = true;
  29147. };
  29148. MaterialDefines.prototype.rebuild = function () {
  29149. if (this._keys) {
  29150. delete this._keys;
  29151. }
  29152. this._keys = [];
  29153. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29154. var key = _a[_i];
  29155. if (key[0] === "_") {
  29156. continue;
  29157. }
  29158. this._keys.push(key);
  29159. }
  29160. };
  29161. MaterialDefines.prototype.isEqual = function (other) {
  29162. if (this._keys.length !== other._keys.length) {
  29163. return false;
  29164. }
  29165. for (var index = 0; index < this._keys.length; index++) {
  29166. var prop = this._keys[index];
  29167. if (this[prop] !== other[prop]) {
  29168. return false;
  29169. }
  29170. }
  29171. return true;
  29172. };
  29173. MaterialDefines.prototype.cloneTo = function (other) {
  29174. if (this._keys.length !== other._keys.length) {
  29175. other._keys = this._keys.slice(0);
  29176. }
  29177. for (var index = 0; index < this._keys.length; index++) {
  29178. var prop = this._keys[index];
  29179. other[prop] = this[prop];
  29180. }
  29181. };
  29182. MaterialDefines.prototype.reset = function () {
  29183. for (var index = 0; index < this._keys.length; index++) {
  29184. var prop = this._keys[index];
  29185. if (typeof (this[prop]) === "number") {
  29186. this[prop] = 0;
  29187. }
  29188. else {
  29189. this[prop] = false;
  29190. }
  29191. }
  29192. };
  29193. MaterialDefines.prototype.toString = function () {
  29194. var result = "";
  29195. for (var index = 0; index < this._keys.length; index++) {
  29196. var prop = this._keys[index];
  29197. var value = this[prop];
  29198. if (typeof (value) === "number") {
  29199. result += "#define " + prop + " " + this[prop] + "\n";
  29200. }
  29201. else if (value) {
  29202. result += "#define " + prop + "\n";
  29203. }
  29204. }
  29205. return result;
  29206. };
  29207. return MaterialDefines;
  29208. }());
  29209. BABYLON.MaterialDefines = MaterialDefines;
  29210. var Material = /** @class */ (function () {
  29211. function Material(name, scene, doNotAdd) {
  29212. this.checkReadyOnEveryCall = false;
  29213. this.checkReadyOnlyOnce = false;
  29214. this.state = "";
  29215. this._alpha = 1.0;
  29216. this._backFaceCulling = true;
  29217. this.doNotSerialize = false;
  29218. this.storeEffectOnSubMeshes = false;
  29219. /**
  29220. * An event triggered when the material is disposed.
  29221. * @type {BABYLON.Observable}
  29222. */
  29223. this.onDisposeObservable = new BABYLON.Observable();
  29224. /**
  29225. * An event triggered when the material is bound.
  29226. * @type {BABYLON.Observable}
  29227. */
  29228. this.onBindObservable = new BABYLON.Observable();
  29229. /**
  29230. * An event triggered when the material is unbound.
  29231. * @type {BABYLON.Observable}
  29232. */
  29233. this.onUnBindObservable = new BABYLON.Observable();
  29234. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29235. this._needDepthPrePass = false;
  29236. this.disableDepthWrite = false;
  29237. this.forceDepthWrite = false;
  29238. this.separateCullingPass = false;
  29239. this._fogEnabled = true;
  29240. this.pointSize = 1.0;
  29241. this.zOffset = 0;
  29242. this._wasPreviouslyReady = false;
  29243. this._fillMode = Material.TriangleFillMode;
  29244. this.name = name;
  29245. this.id = name || BABYLON.Tools.RandomId();
  29246. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29247. if (this._scene.useRightHandedSystem) {
  29248. this.sideOrientation = Material.ClockWiseSideOrientation;
  29249. }
  29250. else {
  29251. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29252. }
  29253. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29254. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29255. if (!doNotAdd) {
  29256. this._scene.materials.push(this);
  29257. }
  29258. }
  29259. Object.defineProperty(Material, "TriangleFillMode", {
  29260. get: function () {
  29261. return Material._TriangleFillMode;
  29262. },
  29263. enumerable: true,
  29264. configurable: true
  29265. });
  29266. Object.defineProperty(Material, "WireFrameFillMode", {
  29267. get: function () {
  29268. return Material._WireFrameFillMode;
  29269. },
  29270. enumerable: true,
  29271. configurable: true
  29272. });
  29273. Object.defineProperty(Material, "PointFillMode", {
  29274. get: function () {
  29275. return Material._PointFillMode;
  29276. },
  29277. enumerable: true,
  29278. configurable: true
  29279. });
  29280. Object.defineProperty(Material, "PointListDrawMode", {
  29281. get: function () {
  29282. return Material._PointListDrawMode;
  29283. },
  29284. enumerable: true,
  29285. configurable: true
  29286. });
  29287. Object.defineProperty(Material, "LineListDrawMode", {
  29288. get: function () {
  29289. return Material._LineListDrawMode;
  29290. },
  29291. enumerable: true,
  29292. configurable: true
  29293. });
  29294. Object.defineProperty(Material, "LineLoopDrawMode", {
  29295. get: function () {
  29296. return Material._LineLoopDrawMode;
  29297. },
  29298. enumerable: true,
  29299. configurable: true
  29300. });
  29301. Object.defineProperty(Material, "LineStripDrawMode", {
  29302. get: function () {
  29303. return Material._LineStripDrawMode;
  29304. },
  29305. enumerable: true,
  29306. configurable: true
  29307. });
  29308. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29309. get: function () {
  29310. return Material._TriangleStripDrawMode;
  29311. },
  29312. enumerable: true,
  29313. configurable: true
  29314. });
  29315. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29316. get: function () {
  29317. return Material._TriangleFanDrawMode;
  29318. },
  29319. enumerable: true,
  29320. configurable: true
  29321. });
  29322. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29323. get: function () {
  29324. return Material._ClockWiseSideOrientation;
  29325. },
  29326. enumerable: true,
  29327. configurable: true
  29328. });
  29329. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29330. get: function () {
  29331. return Material._CounterClockWiseSideOrientation;
  29332. },
  29333. enumerable: true,
  29334. configurable: true
  29335. });
  29336. Object.defineProperty(Material, "TextureDirtyFlag", {
  29337. get: function () {
  29338. return Material._TextureDirtyFlag;
  29339. },
  29340. enumerable: true,
  29341. configurable: true
  29342. });
  29343. Object.defineProperty(Material, "LightDirtyFlag", {
  29344. get: function () {
  29345. return Material._LightDirtyFlag;
  29346. },
  29347. enumerable: true,
  29348. configurable: true
  29349. });
  29350. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29351. get: function () {
  29352. return Material._FresnelDirtyFlag;
  29353. },
  29354. enumerable: true,
  29355. configurable: true
  29356. });
  29357. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29358. get: function () {
  29359. return Material._AttributesDirtyFlag;
  29360. },
  29361. enumerable: true,
  29362. configurable: true
  29363. });
  29364. Object.defineProperty(Material, "MiscDirtyFlag", {
  29365. get: function () {
  29366. return Material._MiscDirtyFlag;
  29367. },
  29368. enumerable: true,
  29369. configurable: true
  29370. });
  29371. Object.defineProperty(Material.prototype, "alpha", {
  29372. get: function () {
  29373. return this._alpha;
  29374. },
  29375. set: function (value) {
  29376. if (this._alpha === value) {
  29377. return;
  29378. }
  29379. this._alpha = value;
  29380. this.markAsDirty(Material.MiscDirtyFlag);
  29381. },
  29382. enumerable: true,
  29383. configurable: true
  29384. });
  29385. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29386. get: function () {
  29387. return this._backFaceCulling;
  29388. },
  29389. set: function (value) {
  29390. if (this._backFaceCulling === value) {
  29391. return;
  29392. }
  29393. this._backFaceCulling = value;
  29394. this.markAsDirty(Material.TextureDirtyFlag);
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(Material.prototype, "onDispose", {
  29400. set: function (callback) {
  29401. if (this._onDisposeObserver) {
  29402. this.onDisposeObservable.remove(this._onDisposeObserver);
  29403. }
  29404. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29405. },
  29406. enumerable: true,
  29407. configurable: true
  29408. });
  29409. Object.defineProperty(Material.prototype, "onBind", {
  29410. set: function (callback) {
  29411. if (this._onBindObserver) {
  29412. this.onBindObservable.remove(this._onBindObserver);
  29413. }
  29414. this._onBindObserver = this.onBindObservable.add(callback);
  29415. },
  29416. enumerable: true,
  29417. configurable: true
  29418. });
  29419. Object.defineProperty(Material.prototype, "alphaMode", {
  29420. get: function () {
  29421. return this._alphaMode;
  29422. },
  29423. set: function (value) {
  29424. if (this._alphaMode === value) {
  29425. return;
  29426. }
  29427. this._alphaMode = value;
  29428. this.markAsDirty(Material.TextureDirtyFlag);
  29429. },
  29430. enumerable: true,
  29431. configurable: true
  29432. });
  29433. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29434. get: function () {
  29435. return this._needDepthPrePass;
  29436. },
  29437. set: function (value) {
  29438. if (this._needDepthPrePass === value) {
  29439. return;
  29440. }
  29441. this._needDepthPrePass = value;
  29442. if (this._needDepthPrePass) {
  29443. this.checkReadyOnEveryCall = true;
  29444. }
  29445. },
  29446. enumerable: true,
  29447. configurable: true
  29448. });
  29449. Object.defineProperty(Material.prototype, "fogEnabled", {
  29450. get: function () {
  29451. return this._fogEnabled;
  29452. },
  29453. set: function (value) {
  29454. if (this._fogEnabled === value) {
  29455. return;
  29456. }
  29457. this._fogEnabled = value;
  29458. this.markAsDirty(Material.MiscDirtyFlag);
  29459. },
  29460. enumerable: true,
  29461. configurable: true
  29462. });
  29463. Object.defineProperty(Material.prototype, "wireframe", {
  29464. get: function () {
  29465. return this._fillMode === Material.WireFrameFillMode;
  29466. },
  29467. set: function (value) {
  29468. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29469. },
  29470. enumerable: true,
  29471. configurable: true
  29472. });
  29473. Object.defineProperty(Material.prototype, "pointsCloud", {
  29474. get: function () {
  29475. return this._fillMode === Material.PointFillMode;
  29476. },
  29477. set: function (value) {
  29478. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29479. },
  29480. enumerable: true,
  29481. configurable: true
  29482. });
  29483. Object.defineProperty(Material.prototype, "fillMode", {
  29484. get: function () {
  29485. return this._fillMode;
  29486. },
  29487. set: function (value) {
  29488. if (this._fillMode === value) {
  29489. return;
  29490. }
  29491. this._fillMode = value;
  29492. this.markAsDirty(Material.MiscDirtyFlag);
  29493. },
  29494. enumerable: true,
  29495. configurable: true
  29496. });
  29497. /**
  29498. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29499. * subclasses should override adding information pertainent to themselves
  29500. */
  29501. Material.prototype.toString = function (fullDetails) {
  29502. var ret = "Name: " + this.name;
  29503. if (fullDetails) {
  29504. }
  29505. return ret;
  29506. };
  29507. /**
  29508. * Child classes can use it to update shaders
  29509. */
  29510. Material.prototype.getClassName = function () {
  29511. return "Material";
  29512. };
  29513. Object.defineProperty(Material.prototype, "isFrozen", {
  29514. get: function () {
  29515. return this.checkReadyOnlyOnce;
  29516. },
  29517. enumerable: true,
  29518. configurable: true
  29519. });
  29520. Material.prototype.freeze = function () {
  29521. this.checkReadyOnlyOnce = true;
  29522. };
  29523. Material.prototype.unfreeze = function () {
  29524. this.checkReadyOnlyOnce = false;
  29525. };
  29526. Material.prototype.isReady = function (mesh, useInstances) {
  29527. return true;
  29528. };
  29529. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29530. return false;
  29531. };
  29532. Material.prototype.getEffect = function () {
  29533. return this._effect;
  29534. };
  29535. Material.prototype.getScene = function () {
  29536. return this._scene;
  29537. };
  29538. Material.prototype.needAlphaBlending = function () {
  29539. return (this.alpha < 1.0);
  29540. };
  29541. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29542. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29543. };
  29544. Material.prototype.needAlphaTesting = function () {
  29545. return false;
  29546. };
  29547. Material.prototype.getAlphaTestTexture = function () {
  29548. return null;
  29549. };
  29550. Material.prototype.markDirty = function () {
  29551. this._wasPreviouslyReady = false;
  29552. };
  29553. Material.prototype._preBind = function (effect, overrideOrientation) {
  29554. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29555. var engine = this._scene.getEngine();
  29556. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29557. var reverse = orientation === Material.ClockWiseSideOrientation;
  29558. engine.enableEffect(effect ? effect : this._effect);
  29559. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29560. return reverse;
  29561. };
  29562. Material.prototype.bind = function (world, mesh) {
  29563. };
  29564. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29565. };
  29566. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29567. };
  29568. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29569. sceneUbo.bindToEffect(effect, "Scene");
  29570. };
  29571. Material.prototype.bindView = function (effect) {
  29572. if (!this._useUBO) {
  29573. effect.setMatrix("view", this.getScene().getViewMatrix());
  29574. }
  29575. else {
  29576. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29577. }
  29578. };
  29579. Material.prototype.bindViewProjection = function (effect) {
  29580. if (!this._useUBO) {
  29581. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29582. }
  29583. else {
  29584. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29585. }
  29586. };
  29587. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29588. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29589. };
  29590. Material.prototype._afterBind = function (mesh) {
  29591. this._scene._cachedMaterial = this;
  29592. if (mesh) {
  29593. this._scene._cachedVisibility = mesh.visibility;
  29594. }
  29595. else {
  29596. this._scene._cachedVisibility = 1;
  29597. }
  29598. if (mesh) {
  29599. this.onBindObservable.notifyObservers(mesh);
  29600. }
  29601. if (this.disableDepthWrite) {
  29602. var engine = this._scene.getEngine();
  29603. this._cachedDepthWriteState = engine.getDepthWrite();
  29604. engine.setDepthWrite(false);
  29605. }
  29606. };
  29607. Material.prototype.unbind = function () {
  29608. this.onUnBindObservable.notifyObservers(this);
  29609. if (this.disableDepthWrite) {
  29610. var engine = this._scene.getEngine();
  29611. engine.setDepthWrite(this._cachedDepthWriteState);
  29612. }
  29613. };
  29614. Material.prototype.getActiveTextures = function () {
  29615. return [];
  29616. };
  29617. Material.prototype.hasTexture = function (texture) {
  29618. return false;
  29619. };
  29620. Material.prototype.clone = function (name) {
  29621. return null;
  29622. };
  29623. Material.prototype.getBindedMeshes = function () {
  29624. var result = new Array();
  29625. for (var index = 0; index < this._scene.meshes.length; index++) {
  29626. var mesh = this._scene.meshes[index];
  29627. if (mesh.material === this) {
  29628. result.push(mesh);
  29629. }
  29630. }
  29631. return result;
  29632. };
  29633. /**
  29634. * Force shader compilation including textures ready check
  29635. */
  29636. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29637. var _this = this;
  29638. var localOptions = __assign({ clipPlane: false }, options);
  29639. var subMesh = new BABYLON.BaseSubMesh();
  29640. var scene = this.getScene();
  29641. var checkReady = function () {
  29642. if (!_this._scene || !_this._scene.getEngine()) {
  29643. return;
  29644. }
  29645. if (subMesh._materialDefines) {
  29646. subMesh._materialDefines._renderId = -1;
  29647. }
  29648. var clipPlaneState = scene.clipPlane;
  29649. if (localOptions.clipPlane) {
  29650. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29651. }
  29652. if (_this.storeEffectOnSubMeshes) {
  29653. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29654. if (onCompiled) {
  29655. onCompiled(_this);
  29656. }
  29657. }
  29658. else {
  29659. setTimeout(checkReady, 16);
  29660. }
  29661. }
  29662. else {
  29663. if (_this.isReady(mesh)) {
  29664. if (onCompiled) {
  29665. onCompiled(_this);
  29666. }
  29667. }
  29668. else {
  29669. setTimeout(checkReady, 16);
  29670. }
  29671. }
  29672. if (options && options.clipPlane) {
  29673. scene.clipPlane = clipPlaneState;
  29674. }
  29675. };
  29676. checkReady();
  29677. };
  29678. Material.prototype.markAsDirty = function (flag) {
  29679. if (flag & Material.TextureDirtyFlag) {
  29680. this._markAllSubMeshesAsTexturesDirty();
  29681. }
  29682. if (flag & Material.LightDirtyFlag) {
  29683. this._markAllSubMeshesAsLightsDirty();
  29684. }
  29685. if (flag & Material.FresnelDirtyFlag) {
  29686. this._markAllSubMeshesAsFresnelDirty();
  29687. }
  29688. if (flag & Material.AttributesDirtyFlag) {
  29689. this._markAllSubMeshesAsAttributesDirty();
  29690. }
  29691. if (flag & Material.MiscDirtyFlag) {
  29692. this._markAllSubMeshesAsMiscDirty();
  29693. }
  29694. this.getScene().resetCachedMaterial();
  29695. };
  29696. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29697. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29698. var mesh = _a[_i];
  29699. if (!mesh.subMeshes) {
  29700. continue;
  29701. }
  29702. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29703. var subMesh = _c[_b];
  29704. if (subMesh.getMaterial() !== this) {
  29705. continue;
  29706. }
  29707. if (!subMesh._materialDefines) {
  29708. continue;
  29709. }
  29710. func(subMesh._materialDefines);
  29711. }
  29712. }
  29713. };
  29714. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29715. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29716. };
  29717. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29718. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29719. };
  29720. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29721. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29722. };
  29723. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29724. this._markAllSubMeshesAsDirty(function (defines) {
  29725. defines.markAsFresnelDirty();
  29726. defines.markAsMiscDirty();
  29727. });
  29728. };
  29729. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29730. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29731. };
  29732. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29733. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29734. };
  29735. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29736. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29737. };
  29738. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29739. this._markAllSubMeshesAsDirty(function (defines) {
  29740. defines.markAsTexturesDirty();
  29741. defines.markAsMiscDirty();
  29742. });
  29743. };
  29744. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29745. // Animations
  29746. this.getScene().stopAnimation(this);
  29747. // Remove from scene
  29748. var index = this._scene.materials.indexOf(this);
  29749. if (index >= 0) {
  29750. this._scene.materials.splice(index, 1);
  29751. }
  29752. // Remove from meshes
  29753. for (index = 0; index < this._scene.meshes.length; index++) {
  29754. var mesh = this._scene.meshes[index];
  29755. if (mesh.material === this) {
  29756. mesh.material = null;
  29757. if (mesh.geometry) {
  29758. var geometry = (mesh.geometry);
  29759. if (this.storeEffectOnSubMeshes) {
  29760. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29761. var subMesh = _a[_i];
  29762. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29763. if (forceDisposeEffect && subMesh._materialEffect) {
  29764. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29765. }
  29766. }
  29767. }
  29768. else {
  29769. geometry._releaseVertexArrayObject(this._effect);
  29770. }
  29771. }
  29772. }
  29773. }
  29774. this._uniformBuffer.dispose();
  29775. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29776. if (forceDisposeEffect && this._effect) {
  29777. if (!this.storeEffectOnSubMeshes) {
  29778. this._scene.getEngine()._releaseEffect(this._effect);
  29779. }
  29780. this._effect = null;
  29781. }
  29782. // Callback
  29783. this.onDisposeObservable.notifyObservers(this);
  29784. this.onDisposeObservable.clear();
  29785. this.onBindObservable.clear();
  29786. this.onUnBindObservable.clear();
  29787. };
  29788. Material.prototype.serialize = function () {
  29789. return BABYLON.SerializationHelper.Serialize(this);
  29790. };
  29791. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29792. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29793. multiMaterial.id = parsedMultiMaterial.id;
  29794. if (BABYLON.Tags) {
  29795. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29796. }
  29797. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29798. var subMatId = parsedMultiMaterial.materials[matIndex];
  29799. if (subMatId) {
  29800. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29801. }
  29802. else {
  29803. multiMaterial.subMaterials.push(null);
  29804. }
  29805. }
  29806. return multiMaterial;
  29807. };
  29808. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29809. if (!parsedMaterial.customType) {
  29810. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29811. }
  29812. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29813. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29814. if (!BABYLON.LegacyPBRMaterial) {
  29815. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29816. return;
  29817. }
  29818. }
  29819. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29820. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29821. ;
  29822. };
  29823. // Triangle views
  29824. Material._TriangleFillMode = 0;
  29825. Material._WireFrameFillMode = 1;
  29826. Material._PointFillMode = 2;
  29827. // Draw modes
  29828. Material._PointListDrawMode = 3;
  29829. Material._LineListDrawMode = 4;
  29830. Material._LineLoopDrawMode = 5;
  29831. Material._LineStripDrawMode = 6;
  29832. Material._TriangleStripDrawMode = 7;
  29833. Material._TriangleFanDrawMode = 8;
  29834. Material._ClockWiseSideOrientation = 0;
  29835. Material._CounterClockWiseSideOrientation = 1;
  29836. Material._TextureDirtyFlag = 1;
  29837. Material._LightDirtyFlag = 2;
  29838. Material._FresnelDirtyFlag = 4;
  29839. Material._AttributesDirtyFlag = 8;
  29840. Material._MiscDirtyFlag = 16;
  29841. __decorate([
  29842. BABYLON.serialize()
  29843. ], Material.prototype, "id", void 0);
  29844. __decorate([
  29845. BABYLON.serialize()
  29846. ], Material.prototype, "name", void 0);
  29847. __decorate([
  29848. BABYLON.serialize()
  29849. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29850. __decorate([
  29851. BABYLON.serialize()
  29852. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29853. __decorate([
  29854. BABYLON.serialize()
  29855. ], Material.prototype, "state", void 0);
  29856. __decorate([
  29857. BABYLON.serialize("alpha")
  29858. ], Material.prototype, "_alpha", void 0);
  29859. __decorate([
  29860. BABYLON.serialize("backFaceCulling")
  29861. ], Material.prototype, "_backFaceCulling", void 0);
  29862. __decorate([
  29863. BABYLON.serialize()
  29864. ], Material.prototype, "sideOrientation", void 0);
  29865. __decorate([
  29866. BABYLON.serialize("alphaMode")
  29867. ], Material.prototype, "_alphaMode", void 0);
  29868. __decorate([
  29869. BABYLON.serialize()
  29870. ], Material.prototype, "_needDepthPrePass", void 0);
  29871. __decorate([
  29872. BABYLON.serialize()
  29873. ], Material.prototype, "disableDepthWrite", void 0);
  29874. __decorate([
  29875. BABYLON.serialize()
  29876. ], Material.prototype, "forceDepthWrite", void 0);
  29877. __decorate([
  29878. BABYLON.serialize()
  29879. ], Material.prototype, "separateCullingPass", void 0);
  29880. __decorate([
  29881. BABYLON.serialize("fogEnabled")
  29882. ], Material.prototype, "_fogEnabled", void 0);
  29883. __decorate([
  29884. BABYLON.serialize()
  29885. ], Material.prototype, "pointSize", void 0);
  29886. __decorate([
  29887. BABYLON.serialize()
  29888. ], Material.prototype, "zOffset", void 0);
  29889. __decorate([
  29890. BABYLON.serialize()
  29891. ], Material.prototype, "wireframe", null);
  29892. __decorate([
  29893. BABYLON.serialize()
  29894. ], Material.prototype, "pointsCloud", null);
  29895. __decorate([
  29896. BABYLON.serialize()
  29897. ], Material.prototype, "fillMode", null);
  29898. return Material;
  29899. }());
  29900. BABYLON.Material = Material;
  29901. })(BABYLON || (BABYLON = {}));
  29902. //# sourceMappingURL=babylon.material.js.map
  29903. var BABYLON;
  29904. (function (BABYLON) {
  29905. var UniformBuffer = /** @class */ (function () {
  29906. /**
  29907. * Uniform buffer objects.
  29908. *
  29909. * Handles blocks of uniform on the GPU.
  29910. *
  29911. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29912. *
  29913. * For more information, please refer to :
  29914. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29915. */
  29916. function UniformBuffer(engine, data, dynamic) {
  29917. this._engine = engine;
  29918. this._noUBO = !engine.supportsUniformBuffers;
  29919. this._dynamic = dynamic;
  29920. this._data = data || [];
  29921. this._uniformLocations = {};
  29922. this._uniformSizes = {};
  29923. this._uniformLocationPointer = 0;
  29924. this._needSync = false;
  29925. if (this._noUBO) {
  29926. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29927. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29928. this.updateFloat = this._updateFloatForEffect;
  29929. this.updateFloat2 = this._updateFloat2ForEffect;
  29930. this.updateFloat3 = this._updateFloat3ForEffect;
  29931. this.updateFloat4 = this._updateFloat4ForEffect;
  29932. this.updateMatrix = this._updateMatrixForEffect;
  29933. this.updateVector3 = this._updateVector3ForEffect;
  29934. this.updateVector4 = this._updateVector4ForEffect;
  29935. this.updateColor3 = this._updateColor3ForEffect;
  29936. this.updateColor4 = this._updateColor4ForEffect;
  29937. }
  29938. else {
  29939. this._engine._uniformBuffers.push(this);
  29940. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29941. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29942. this.updateFloat = this._updateFloatForUniform;
  29943. this.updateFloat2 = this._updateFloat2ForUniform;
  29944. this.updateFloat3 = this._updateFloat3ForUniform;
  29945. this.updateFloat4 = this._updateFloat4ForUniform;
  29946. this.updateMatrix = this._updateMatrixForUniform;
  29947. this.updateVector3 = this._updateVector3ForUniform;
  29948. this.updateVector4 = this._updateVector4ForUniform;
  29949. this.updateColor3 = this._updateColor3ForUniform;
  29950. this.updateColor4 = this._updateColor4ForUniform;
  29951. }
  29952. }
  29953. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29954. // Properties
  29955. /**
  29956. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29957. * or just falling back on setUniformXXX calls.
  29958. */
  29959. get: function () {
  29960. return !this._noUBO;
  29961. },
  29962. enumerable: true,
  29963. configurable: true
  29964. });
  29965. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29966. /**
  29967. * Indicates if the WebGL underlying uniform buffer is in sync
  29968. * with the javascript cache data.
  29969. */
  29970. get: function () {
  29971. return !this._needSync;
  29972. },
  29973. enumerable: true,
  29974. configurable: true
  29975. });
  29976. /**
  29977. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29978. * Also, a dynamic UniformBuffer will disable cache verification and always
  29979. * update the underlying WebGL uniform buffer to the GPU.
  29980. */
  29981. UniformBuffer.prototype.isDynamic = function () {
  29982. return this._dynamic !== undefined;
  29983. };
  29984. /**
  29985. * The data cache on JS side.
  29986. */
  29987. UniformBuffer.prototype.getData = function () {
  29988. return this._bufferData;
  29989. };
  29990. /**
  29991. * The underlying WebGL Uniform buffer.
  29992. */
  29993. UniformBuffer.prototype.getBuffer = function () {
  29994. return this._buffer;
  29995. };
  29996. /**
  29997. * std140 layout specifies how to align data within an UBO structure.
  29998. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29999. * for specs.
  30000. */
  30001. UniformBuffer.prototype._fillAlignment = function (size) {
  30002. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  30003. // and 4x4 matrices
  30004. // TODO : change if other types are used
  30005. var alignment;
  30006. if (size <= 2) {
  30007. alignment = size;
  30008. }
  30009. else {
  30010. alignment = 4;
  30011. }
  30012. if ((this._uniformLocationPointer % alignment) !== 0) {
  30013. var oldPointer = this._uniformLocationPointer;
  30014. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  30015. var diff = this._uniformLocationPointer - oldPointer;
  30016. for (var i = 0; i < diff; i++) {
  30017. this._data.push(0);
  30018. }
  30019. }
  30020. };
  30021. /**
  30022. * Adds an uniform in the buffer.
  30023. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  30024. * for the layout to be correct !
  30025. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30026. * @param {number|number[]} size Data size, or data directly.
  30027. */
  30028. UniformBuffer.prototype.addUniform = function (name, size) {
  30029. if (this._noUBO) {
  30030. return;
  30031. }
  30032. if (this._uniformLocations[name] !== undefined) {
  30033. // Already existing uniform
  30034. return;
  30035. }
  30036. // This function must be called in the order of the shader layout !
  30037. // size can be the size of the uniform, or data directly
  30038. var data;
  30039. if (size instanceof Array) {
  30040. data = size;
  30041. size = data.length;
  30042. }
  30043. else {
  30044. size = size;
  30045. data = [];
  30046. // Fill with zeros
  30047. for (var i = 0; i < size; i++) {
  30048. data.push(0);
  30049. }
  30050. }
  30051. this._fillAlignment(size);
  30052. this._uniformSizes[name] = size;
  30053. this._uniformLocations[name] = this._uniformLocationPointer;
  30054. this._uniformLocationPointer += size;
  30055. for (var i = 0; i < size; i++) {
  30056. this._data.push(data[i]);
  30057. }
  30058. this._needSync = true;
  30059. };
  30060. /**
  30061. * Wrapper for addUniform.
  30062. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30063. * @param {Matrix} mat A 4x4 matrix.
  30064. */
  30065. UniformBuffer.prototype.addMatrix = function (name, mat) {
  30066. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  30067. };
  30068. /**
  30069. * Wrapper for addUniform.
  30070. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30071. * @param {number} x
  30072. * @param {number} y
  30073. */
  30074. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  30075. var temp = [x, y];
  30076. this.addUniform(name, temp);
  30077. };
  30078. /**
  30079. * Wrapper for addUniform.
  30080. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30081. * @param {number} x
  30082. * @param {number} y
  30083. * @param {number} z
  30084. */
  30085. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  30086. var temp = [x, y, z];
  30087. this.addUniform(name, temp);
  30088. };
  30089. /**
  30090. * Wrapper for addUniform.
  30091. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30092. * @param {Color3} color
  30093. */
  30094. UniformBuffer.prototype.addColor3 = function (name, color) {
  30095. var temp = new Array();
  30096. color.toArray(temp);
  30097. this.addUniform(name, temp);
  30098. };
  30099. /**
  30100. * Wrapper for addUniform.
  30101. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30102. * @param {Color3} color
  30103. * @param {number} alpha
  30104. */
  30105. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  30106. var temp = new Array();
  30107. color.toArray(temp);
  30108. temp.push(alpha);
  30109. this.addUniform(name, temp);
  30110. };
  30111. /**
  30112. * Wrapper for addUniform.
  30113. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30114. * @param {Vector3} vector
  30115. */
  30116. UniformBuffer.prototype.addVector3 = function (name, vector) {
  30117. var temp = new Array();
  30118. vector.toArray(temp);
  30119. this.addUniform(name, temp);
  30120. };
  30121. /**
  30122. * Wrapper for addUniform.
  30123. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30124. */
  30125. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  30126. this.addUniform(name, 12);
  30127. };
  30128. /**
  30129. * Wrapper for addUniform.
  30130. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30131. */
  30132. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30133. this.addUniform(name, 8);
  30134. };
  30135. /**
  30136. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30137. */
  30138. UniformBuffer.prototype.create = function () {
  30139. if (this._noUBO) {
  30140. return;
  30141. }
  30142. if (this._buffer) {
  30143. return; // nothing to do
  30144. }
  30145. // See spec, alignment must be filled as a vec4
  30146. this._fillAlignment(4);
  30147. this._bufferData = new Float32Array(this._data);
  30148. this._rebuild();
  30149. this._needSync = true;
  30150. };
  30151. UniformBuffer.prototype._rebuild = function () {
  30152. if (this._noUBO) {
  30153. return;
  30154. }
  30155. if (this._dynamic) {
  30156. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30157. }
  30158. else {
  30159. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30160. }
  30161. };
  30162. /**
  30163. * Updates the WebGL Uniform Buffer on the GPU.
  30164. * If the `dynamic` flag is set to true, no cache comparison is done.
  30165. * Otherwise, the buffer will be updated only if the cache differs.
  30166. */
  30167. UniformBuffer.prototype.update = function () {
  30168. if (!this._buffer) {
  30169. this.create();
  30170. return;
  30171. }
  30172. if (!this._dynamic && !this._needSync) {
  30173. return;
  30174. }
  30175. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30176. this._needSync = false;
  30177. };
  30178. /**
  30179. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30180. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30181. * @param {number[]|Float32Array} data Flattened data
  30182. * @param {number} size Size of the data.
  30183. */
  30184. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30185. var location = this._uniformLocations[uniformName];
  30186. if (location === undefined) {
  30187. if (this._buffer) {
  30188. // Cannot add an uniform if the buffer is already created
  30189. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30190. return;
  30191. }
  30192. this.addUniform(uniformName, size);
  30193. location = this._uniformLocations[uniformName];
  30194. }
  30195. if (!this._buffer) {
  30196. this.create();
  30197. }
  30198. if (!this._dynamic) {
  30199. // Cache for static uniform buffers
  30200. var changed = false;
  30201. for (var i = 0; i < size; i++) {
  30202. if (this._bufferData[location + i] !== data[i]) {
  30203. changed = true;
  30204. this._bufferData[location + i] = data[i];
  30205. }
  30206. }
  30207. this._needSync = this._needSync || changed;
  30208. }
  30209. else {
  30210. // No cache for dynamic
  30211. for (var i = 0; i < size; i++) {
  30212. this._bufferData[location + i] = data[i];
  30213. }
  30214. }
  30215. };
  30216. // Update methods
  30217. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30218. // To match std140, matrix must be realigned
  30219. for (var i = 0; i < 3; i++) {
  30220. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30221. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30222. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30223. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30224. }
  30225. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30226. };
  30227. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30228. this._currentEffect.setMatrix3x3(name, matrix);
  30229. };
  30230. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30231. this._currentEffect.setMatrix2x2(name, matrix);
  30232. };
  30233. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30234. // To match std140, matrix must be realigned
  30235. for (var i = 0; i < 2; i++) {
  30236. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30237. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30238. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30239. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30240. }
  30241. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30242. };
  30243. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30244. this._currentEffect.setFloat(name, x);
  30245. };
  30246. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30247. UniformBuffer._tempBuffer[0] = x;
  30248. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30249. };
  30250. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30251. if (suffix === void 0) { suffix = ""; }
  30252. this._currentEffect.setFloat2(name + suffix, x, y);
  30253. };
  30254. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30255. if (suffix === void 0) { suffix = ""; }
  30256. UniformBuffer._tempBuffer[0] = x;
  30257. UniformBuffer._tempBuffer[1] = y;
  30258. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30259. };
  30260. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30261. if (suffix === void 0) { suffix = ""; }
  30262. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30263. };
  30264. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30265. if (suffix === void 0) { suffix = ""; }
  30266. UniformBuffer._tempBuffer[0] = x;
  30267. UniformBuffer._tempBuffer[1] = y;
  30268. UniformBuffer._tempBuffer[2] = z;
  30269. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30270. };
  30271. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30272. if (suffix === void 0) { suffix = ""; }
  30273. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30274. };
  30275. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30276. if (suffix === void 0) { suffix = ""; }
  30277. UniformBuffer._tempBuffer[0] = x;
  30278. UniformBuffer._tempBuffer[1] = y;
  30279. UniformBuffer._tempBuffer[2] = z;
  30280. UniformBuffer._tempBuffer[3] = w;
  30281. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30282. };
  30283. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30284. this._currentEffect.setMatrix(name, mat);
  30285. };
  30286. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30287. this.updateUniform(name, mat.toArray(), 16);
  30288. };
  30289. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30290. this._currentEffect.setVector3(name, vector);
  30291. };
  30292. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30293. vector.toArray(UniformBuffer._tempBuffer);
  30294. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30295. };
  30296. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30297. this._currentEffect.setVector4(name, vector);
  30298. };
  30299. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30300. vector.toArray(UniformBuffer._tempBuffer);
  30301. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30302. };
  30303. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30304. if (suffix === void 0) { suffix = ""; }
  30305. this._currentEffect.setColor3(name + suffix, color);
  30306. };
  30307. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30308. if (suffix === void 0) { suffix = ""; }
  30309. color.toArray(UniformBuffer._tempBuffer);
  30310. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30311. };
  30312. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30313. if (suffix === void 0) { suffix = ""; }
  30314. this._currentEffect.setColor4(name + suffix, color, alpha);
  30315. };
  30316. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30317. if (suffix === void 0) { suffix = ""; }
  30318. color.toArray(UniformBuffer._tempBuffer);
  30319. UniformBuffer._tempBuffer[3] = alpha;
  30320. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30321. };
  30322. /**
  30323. * Sets a sampler uniform on the effect.
  30324. * @param {string} name Name of the sampler.
  30325. * @param {Texture} texture
  30326. */
  30327. UniformBuffer.prototype.setTexture = function (name, texture) {
  30328. this._currentEffect.setTexture(name, texture);
  30329. };
  30330. /**
  30331. * Directly updates the value of the uniform in the cache AND on the GPU.
  30332. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30333. * @param {number[]|Float32Array} data Flattened data
  30334. */
  30335. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30336. this.updateUniform(uniformName, data, data.length);
  30337. this.update();
  30338. };
  30339. /**
  30340. * Binds this uniform buffer to an effect.
  30341. * @param {Effect} effect
  30342. * @param {string} name Name of the uniform block in the shader.
  30343. */
  30344. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30345. this._currentEffect = effect;
  30346. if (this._noUBO || !this._buffer) {
  30347. return;
  30348. }
  30349. effect.bindUniformBuffer(this._buffer, name);
  30350. };
  30351. /**
  30352. * Disposes the uniform buffer.
  30353. */
  30354. UniformBuffer.prototype.dispose = function () {
  30355. if (this._noUBO) {
  30356. return;
  30357. }
  30358. var index = this._engine._uniformBuffers.indexOf(this);
  30359. if (index !== -1) {
  30360. this._engine._uniformBuffers.splice(index, 1);
  30361. }
  30362. if (!this._buffer) {
  30363. return;
  30364. }
  30365. if (this._engine._releaseBuffer(this._buffer)) {
  30366. this._buffer = null;
  30367. }
  30368. };
  30369. // Pool for avoiding memory leaks
  30370. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30371. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30372. return UniformBuffer;
  30373. }());
  30374. BABYLON.UniformBuffer = UniformBuffer;
  30375. })(BABYLON || (BABYLON = {}));
  30376. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30377. var BABYLON;
  30378. (function (BABYLON) {
  30379. var VertexData = /** @class */ (function () {
  30380. function VertexData() {
  30381. }
  30382. VertexData.prototype.set = function (data, kind) {
  30383. switch (kind) {
  30384. case BABYLON.VertexBuffer.PositionKind:
  30385. this.positions = data;
  30386. break;
  30387. case BABYLON.VertexBuffer.NormalKind:
  30388. this.normals = data;
  30389. break;
  30390. case BABYLON.VertexBuffer.TangentKind:
  30391. this.tangents = data;
  30392. break;
  30393. case BABYLON.VertexBuffer.UVKind:
  30394. this.uvs = data;
  30395. break;
  30396. case BABYLON.VertexBuffer.UV2Kind:
  30397. this.uvs2 = data;
  30398. break;
  30399. case BABYLON.VertexBuffer.UV3Kind:
  30400. this.uvs3 = data;
  30401. break;
  30402. case BABYLON.VertexBuffer.UV4Kind:
  30403. this.uvs4 = data;
  30404. break;
  30405. case BABYLON.VertexBuffer.UV5Kind:
  30406. this.uvs5 = data;
  30407. break;
  30408. case BABYLON.VertexBuffer.UV6Kind:
  30409. this.uvs6 = data;
  30410. break;
  30411. case BABYLON.VertexBuffer.ColorKind:
  30412. this.colors = data;
  30413. break;
  30414. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30415. this.matricesIndices = data;
  30416. break;
  30417. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30418. this.matricesWeights = data;
  30419. break;
  30420. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30421. this.matricesIndicesExtra = data;
  30422. break;
  30423. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30424. this.matricesWeightsExtra = data;
  30425. break;
  30426. }
  30427. };
  30428. /**
  30429. * Associates the vertexData to the passed Mesh.
  30430. * Sets it as updatable or not (default `false`).
  30431. * Returns the VertexData.
  30432. */
  30433. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30434. this._applyTo(mesh, updatable);
  30435. return this;
  30436. };
  30437. /**
  30438. * Associates the vertexData to the passed Geometry.
  30439. * Sets it as updatable or not (default `false`).
  30440. * Returns the VertexData.
  30441. */
  30442. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30443. this._applyTo(geometry, updatable);
  30444. return this;
  30445. };
  30446. /**
  30447. * Updates the associated mesh.
  30448. * Returns the VertexData.
  30449. */
  30450. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30451. this._update(mesh);
  30452. return this;
  30453. };
  30454. /**
  30455. * Updates the associated geometry.
  30456. * Returns the VertexData.
  30457. */
  30458. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30459. this._update(geometry);
  30460. return this;
  30461. };
  30462. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30463. if (updatable === void 0) { updatable = false; }
  30464. if (this.positions) {
  30465. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30466. }
  30467. if (this.normals) {
  30468. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30469. }
  30470. if (this.tangents) {
  30471. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30472. }
  30473. if (this.uvs) {
  30474. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30475. }
  30476. if (this.uvs2) {
  30477. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30478. }
  30479. if (this.uvs3) {
  30480. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30481. }
  30482. if (this.uvs4) {
  30483. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30484. }
  30485. if (this.uvs5) {
  30486. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30487. }
  30488. if (this.uvs6) {
  30489. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30490. }
  30491. if (this.colors) {
  30492. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30493. }
  30494. if (this.matricesIndices) {
  30495. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30496. }
  30497. if (this.matricesWeights) {
  30498. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30499. }
  30500. if (this.matricesIndicesExtra) {
  30501. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30502. }
  30503. if (this.matricesWeightsExtra) {
  30504. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30505. }
  30506. if (this.indices) {
  30507. meshOrGeometry.setIndices(this.indices, null, updatable);
  30508. }
  30509. return this;
  30510. };
  30511. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30512. if (this.positions) {
  30513. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30514. }
  30515. if (this.normals) {
  30516. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30517. }
  30518. if (this.tangents) {
  30519. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30520. }
  30521. if (this.uvs) {
  30522. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30523. }
  30524. if (this.uvs2) {
  30525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30526. }
  30527. if (this.uvs3) {
  30528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30529. }
  30530. if (this.uvs4) {
  30531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30532. }
  30533. if (this.uvs5) {
  30534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30535. }
  30536. if (this.uvs6) {
  30537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30538. }
  30539. if (this.colors) {
  30540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30541. }
  30542. if (this.matricesIndices) {
  30543. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30544. }
  30545. if (this.matricesWeights) {
  30546. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30547. }
  30548. if (this.matricesIndicesExtra) {
  30549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30550. }
  30551. if (this.matricesWeightsExtra) {
  30552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30553. }
  30554. if (this.indices) {
  30555. meshOrGeometry.setIndices(this.indices, null);
  30556. }
  30557. return this;
  30558. };
  30559. /**
  30560. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30561. * Returns the VertexData.
  30562. */
  30563. VertexData.prototype.transform = function (matrix) {
  30564. var transformed = BABYLON.Vector3.Zero();
  30565. var index;
  30566. if (this.positions) {
  30567. var position = BABYLON.Vector3.Zero();
  30568. for (index = 0; index < this.positions.length; index += 3) {
  30569. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30570. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30571. this.positions[index] = transformed.x;
  30572. this.positions[index + 1] = transformed.y;
  30573. this.positions[index + 2] = transformed.z;
  30574. }
  30575. }
  30576. if (this.normals) {
  30577. var normal = BABYLON.Vector3.Zero();
  30578. for (index = 0; index < this.normals.length; index += 3) {
  30579. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30580. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30581. this.normals[index] = transformed.x;
  30582. this.normals[index + 1] = transformed.y;
  30583. this.normals[index + 2] = transformed.z;
  30584. }
  30585. }
  30586. if (this.tangents) {
  30587. var tangent = BABYLON.Vector4.Zero();
  30588. var tangentTransformed = BABYLON.Vector4.Zero();
  30589. for (index = 0; index < this.tangents.length; index += 4) {
  30590. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30591. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30592. this.tangents[index] = tangentTransformed.x;
  30593. this.tangents[index + 1] = tangentTransformed.y;
  30594. this.tangents[index + 2] = tangentTransformed.z;
  30595. this.tangents[index + 3] = tangentTransformed.w;
  30596. }
  30597. }
  30598. return this;
  30599. };
  30600. /**
  30601. * Merges the passed VertexData into the current one.
  30602. * Returns the modified VertexData.
  30603. */
  30604. VertexData.prototype.merge = function (other, options) {
  30605. options = options || {};
  30606. if (other.indices) {
  30607. if (!this.indices) {
  30608. this.indices = [];
  30609. }
  30610. var offset = this.positions ? this.positions.length / 3 : 0;
  30611. for (var index = 0; index < other.indices.length; index++) {
  30612. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30613. this.indices.push(other.indices[index] + offset);
  30614. }
  30615. }
  30616. this.positions = this._mergeElement(this.positions, other.positions);
  30617. if (!this.positions) {
  30618. return this;
  30619. }
  30620. var count = this.positions.length / 3;
  30621. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30622. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30623. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30624. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30625. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30626. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30627. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30628. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30629. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30630. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30631. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30632. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30633. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30634. return this;
  30635. };
  30636. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30637. if (length === void 0) { length = 0; }
  30638. if (defaultValue === void 0) { defaultValue = 0; }
  30639. if (!other && !source) {
  30640. return null;
  30641. }
  30642. if (!other) {
  30643. var padding = new Float32Array(source.length);
  30644. padding.fill(defaultValue);
  30645. return this._mergeElement(source, padding, length);
  30646. }
  30647. if (!source) {
  30648. if (length === 0 || length === other.length) {
  30649. return other;
  30650. }
  30651. var padding = new Float32Array(length - other.length);
  30652. padding.fill(defaultValue);
  30653. return this._mergeElement(padding, other, length);
  30654. }
  30655. var len = other.length + source.length;
  30656. var isSrcTypedArray = source instanceof Float32Array;
  30657. var isOthTypedArray = other instanceof Float32Array;
  30658. // use non-loop method when the source is Float32Array
  30659. if (isSrcTypedArray) {
  30660. var ret32 = new Float32Array(len);
  30661. ret32.set(source);
  30662. ret32.set(other, source.length);
  30663. return ret32;
  30664. // source is number[], when other is also use concat
  30665. }
  30666. else if (!isOthTypedArray) {
  30667. return source.concat(other);
  30668. // source is a number[], but other is a Float32Array, loop required
  30669. }
  30670. else {
  30671. var ret = source.slice(0); // copy source to a separate array
  30672. for (var i = 0, len = other.length; i < len; i++) {
  30673. ret.push(other[i]);
  30674. }
  30675. return ret;
  30676. }
  30677. };
  30678. /**
  30679. * Serializes the VertexData.
  30680. * Returns a serialized object.
  30681. */
  30682. VertexData.prototype.serialize = function () {
  30683. var serializationObject = this.serialize();
  30684. if (this.positions) {
  30685. serializationObject.positions = this.positions;
  30686. }
  30687. if (this.normals) {
  30688. serializationObject.normals = this.normals;
  30689. }
  30690. if (this.tangents) {
  30691. serializationObject.tangents = this.tangents;
  30692. }
  30693. if (this.uvs) {
  30694. serializationObject.uvs = this.uvs;
  30695. }
  30696. if (this.uvs2) {
  30697. serializationObject.uvs2 = this.uvs2;
  30698. }
  30699. if (this.uvs3) {
  30700. serializationObject.uvs3 = this.uvs3;
  30701. }
  30702. if (this.uvs4) {
  30703. serializationObject.uvs4 = this.uvs4;
  30704. }
  30705. if (this.uvs5) {
  30706. serializationObject.uvs5 = this.uvs5;
  30707. }
  30708. if (this.uvs6) {
  30709. serializationObject.uvs6 = this.uvs6;
  30710. }
  30711. if (this.colors) {
  30712. serializationObject.colors = this.colors;
  30713. }
  30714. if (this.matricesIndices) {
  30715. serializationObject.matricesIndices = this.matricesIndices;
  30716. serializationObject.matricesIndices._isExpanded = true;
  30717. }
  30718. if (this.matricesWeights) {
  30719. serializationObject.matricesWeights = this.matricesWeights;
  30720. }
  30721. if (this.matricesIndicesExtra) {
  30722. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30723. serializationObject.matricesIndicesExtra._isExpanded = true;
  30724. }
  30725. if (this.matricesWeightsExtra) {
  30726. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30727. }
  30728. serializationObject.indices = this.indices;
  30729. return serializationObject;
  30730. };
  30731. // Statics
  30732. /**
  30733. * Returns the object VertexData associated to the passed mesh.
  30734. */
  30735. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30736. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30737. };
  30738. /**
  30739. * Returns the object VertexData associated to the passed geometry.
  30740. */
  30741. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30742. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30743. };
  30744. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30745. var result = new VertexData();
  30746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30747. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30748. }
  30749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30750. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30751. }
  30752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30753. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30754. }
  30755. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30756. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30757. }
  30758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30759. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30760. }
  30761. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30762. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30763. }
  30764. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30765. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30766. }
  30767. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30768. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30769. }
  30770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30771. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30772. }
  30773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30774. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30775. }
  30776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30777. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30778. }
  30779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30780. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30781. }
  30782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30783. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30784. }
  30785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30786. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30787. }
  30788. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30789. return result;
  30790. };
  30791. /**
  30792. * Creates the vertexData of the Ribbon.
  30793. */
  30794. VertexData.CreateRibbon = function (options) {
  30795. var pathArray = options.pathArray;
  30796. var closeArray = options.closeArray || false;
  30797. var closePath = options.closePath || false;
  30798. var invertUV = options.invertUV || false;
  30799. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30800. var offset = options.offset || defaultOffset;
  30801. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30802. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30803. var customUV = options.uvs;
  30804. var customColors = options.colors;
  30805. var positions = [];
  30806. var indices = [];
  30807. var normals = [];
  30808. var uvs = [];
  30809. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30810. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30811. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30812. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30813. var minlg; // minimal length among all paths from pathArray
  30814. var lg = []; // array of path lengths : nb of vertex per path
  30815. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30816. var p; // path iterator
  30817. var i; // point iterator
  30818. var j; // point iterator
  30819. // if single path in pathArray
  30820. if (pathArray.length < 2) {
  30821. var ar1 = [];
  30822. var ar2 = [];
  30823. for (i = 0; i < pathArray[0].length - offset; i++) {
  30824. ar1.push(pathArray[0][i]);
  30825. ar2.push(pathArray[0][i + offset]);
  30826. }
  30827. pathArray = [ar1, ar2];
  30828. }
  30829. // positions and horizontal distances (u)
  30830. var idc = 0;
  30831. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30832. var path;
  30833. var l;
  30834. minlg = pathArray[0].length;
  30835. var vectlg;
  30836. var dist;
  30837. for (p = 0; p < pathArray.length; p++) {
  30838. uTotalDistance[p] = 0;
  30839. us[p] = [0];
  30840. path = pathArray[p];
  30841. l = path.length;
  30842. minlg = (minlg < l) ? minlg : l;
  30843. j = 0;
  30844. while (j < l) {
  30845. positions.push(path[j].x, path[j].y, path[j].z);
  30846. if (j > 0) {
  30847. vectlg = path[j].subtract(path[j - 1]).length();
  30848. dist = vectlg + uTotalDistance[p];
  30849. us[p].push(dist);
  30850. uTotalDistance[p] = dist;
  30851. }
  30852. j++;
  30853. }
  30854. if (closePath) {
  30855. j--;
  30856. positions.push(path[0].x, path[0].y, path[0].z);
  30857. vectlg = path[j].subtract(path[0]).length();
  30858. dist = vectlg + uTotalDistance[p];
  30859. us[p].push(dist);
  30860. uTotalDistance[p] = dist;
  30861. }
  30862. lg[p] = l + closePathCorr;
  30863. idx[p] = idc;
  30864. idc += (l + closePathCorr);
  30865. }
  30866. // vertical distances (v)
  30867. var path1;
  30868. var path2;
  30869. var vertex1 = null;
  30870. var vertex2 = null;
  30871. for (i = 0; i < minlg + closePathCorr; i++) {
  30872. vTotalDistance[i] = 0;
  30873. vs[i] = [0];
  30874. for (p = 0; p < pathArray.length - 1; p++) {
  30875. path1 = pathArray[p];
  30876. path2 = pathArray[p + 1];
  30877. if (i === minlg) {
  30878. vertex1 = path1[0];
  30879. vertex2 = path2[0];
  30880. }
  30881. else {
  30882. vertex1 = path1[i];
  30883. vertex2 = path2[i];
  30884. }
  30885. vectlg = vertex2.subtract(vertex1).length();
  30886. dist = vectlg + vTotalDistance[i];
  30887. vs[i].push(dist);
  30888. vTotalDistance[i] = dist;
  30889. }
  30890. if (closeArray && vertex2 && vertex1) {
  30891. path1 = pathArray[p];
  30892. path2 = pathArray[0];
  30893. if (i === minlg) {
  30894. vertex2 = path2[0];
  30895. }
  30896. vectlg = vertex2.subtract(vertex1).length();
  30897. dist = vectlg + vTotalDistance[i];
  30898. vTotalDistance[i] = dist;
  30899. }
  30900. }
  30901. // uvs
  30902. var u;
  30903. var v;
  30904. if (customUV) {
  30905. for (p = 0; p < customUV.length; p++) {
  30906. uvs.push(customUV[p].x, customUV[p].y);
  30907. }
  30908. }
  30909. else {
  30910. for (p = 0; p < pathArray.length; p++) {
  30911. for (i = 0; i < minlg + closePathCorr; i++) {
  30912. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30913. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30914. if (invertUV) {
  30915. uvs.push(v, u);
  30916. }
  30917. else {
  30918. uvs.push(u, v);
  30919. }
  30920. }
  30921. }
  30922. }
  30923. // indices
  30924. p = 0; // path index
  30925. var pi = 0; // positions array index
  30926. var l1 = lg[p] - 1; // path1 length
  30927. var l2 = lg[p + 1] - 1; // path2 length
  30928. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30929. var shft = idx[1] - idx[0]; // shift
  30930. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30931. while (pi <= min && p < path1nb) {
  30932. // 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
  30933. indices.push(pi, pi + shft, pi + 1);
  30934. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30935. pi += 1;
  30936. if (pi === min) {
  30937. p++;
  30938. if (p === lg.length - 1) {
  30939. shft = idx[0] - idx[p];
  30940. l1 = lg[p] - 1;
  30941. l2 = lg[0] - 1;
  30942. }
  30943. else {
  30944. shft = idx[p + 1] - idx[p];
  30945. l1 = lg[p] - 1;
  30946. l2 = lg[p + 1] - 1;
  30947. }
  30948. pi = idx[p];
  30949. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30950. }
  30951. }
  30952. // normals
  30953. VertexData.ComputeNormals(positions, indices, normals);
  30954. if (closePath) {
  30955. var indexFirst = 0;
  30956. var indexLast = 0;
  30957. for (p = 0; p < pathArray.length; p++) {
  30958. indexFirst = idx[p] * 3;
  30959. if (p + 1 < pathArray.length) {
  30960. indexLast = (idx[p + 1] - 1) * 3;
  30961. }
  30962. else {
  30963. indexLast = normals.length - 3;
  30964. }
  30965. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30966. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30967. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30968. normals[indexLast] = normals[indexFirst];
  30969. normals[indexLast + 1] = normals[indexFirst + 1];
  30970. normals[indexLast + 2] = normals[indexFirst + 2];
  30971. }
  30972. }
  30973. // sides
  30974. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30975. // Colors
  30976. var colors = null;
  30977. if (customColors) {
  30978. colors = new Float32Array(customColors.length * 4);
  30979. for (var c = 0; c < customColors.length; c++) {
  30980. colors[c * 4] = customColors[c].r;
  30981. colors[c * 4 + 1] = customColors[c].g;
  30982. colors[c * 4 + 2] = customColors[c].b;
  30983. colors[c * 4 + 3] = customColors[c].a;
  30984. }
  30985. }
  30986. // Result
  30987. var vertexData = new VertexData();
  30988. var positions32 = new Float32Array(positions);
  30989. var normals32 = new Float32Array(normals);
  30990. var uvs32 = new Float32Array(uvs);
  30991. vertexData.indices = indices;
  30992. vertexData.positions = positions32;
  30993. vertexData.normals = normals32;
  30994. vertexData.uvs = uvs32;
  30995. if (colors) {
  30996. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30997. }
  30998. if (closePath) {
  30999. vertexData._idx = idx;
  31000. }
  31001. return vertexData;
  31002. };
  31003. /**
  31004. * Creates the VertexData of the Box.
  31005. */
  31006. VertexData.CreateBox = function (options) {
  31007. var normalsSource = [
  31008. new BABYLON.Vector3(0, 0, 1),
  31009. new BABYLON.Vector3(0, 0, -1),
  31010. new BABYLON.Vector3(1, 0, 0),
  31011. new BABYLON.Vector3(-1, 0, 0),
  31012. new BABYLON.Vector3(0, 1, 0),
  31013. new BABYLON.Vector3(0, -1, 0)
  31014. ];
  31015. var indices = [];
  31016. var positions = [];
  31017. var normals = [];
  31018. var uvs = [];
  31019. var width = options.width || options.size || 1;
  31020. var height = options.height || options.size || 1;
  31021. var depth = options.depth || options.size || 1;
  31022. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31023. var faceUV = options.faceUV || new Array(6);
  31024. var faceColors = options.faceColors;
  31025. var colors = [];
  31026. // default face colors and UV if undefined
  31027. for (var f = 0; f < 6; f++) {
  31028. if (faceUV[f] === undefined) {
  31029. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31030. }
  31031. if (faceColors && faceColors[f] === undefined) {
  31032. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31033. }
  31034. }
  31035. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31036. // Create each face in turn.
  31037. for (var index = 0; index < normalsSource.length; index++) {
  31038. var normal = normalsSource[index];
  31039. // Get two vectors perpendicular to the face normal and to each other.
  31040. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31041. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31042. // Six indices (two triangles) per face.
  31043. var verticesLength = positions.length / 3;
  31044. indices.push(verticesLength);
  31045. indices.push(verticesLength + 1);
  31046. indices.push(verticesLength + 2);
  31047. indices.push(verticesLength);
  31048. indices.push(verticesLength + 2);
  31049. indices.push(verticesLength + 3);
  31050. // Four vertices per face.
  31051. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31052. positions.push(vertex.x, vertex.y, vertex.z);
  31053. normals.push(normal.x, normal.y, normal.z);
  31054. uvs.push(faceUV[index].z, faceUV[index].w);
  31055. if (faceColors) {
  31056. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31057. }
  31058. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31059. positions.push(vertex.x, vertex.y, vertex.z);
  31060. normals.push(normal.x, normal.y, normal.z);
  31061. uvs.push(faceUV[index].x, faceUV[index].w);
  31062. if (faceColors) {
  31063. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31064. }
  31065. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31066. positions.push(vertex.x, vertex.y, vertex.z);
  31067. normals.push(normal.x, normal.y, normal.z);
  31068. uvs.push(faceUV[index].x, faceUV[index].y);
  31069. if (faceColors) {
  31070. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31071. }
  31072. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31073. positions.push(vertex.x, vertex.y, vertex.z);
  31074. normals.push(normal.x, normal.y, normal.z);
  31075. uvs.push(faceUV[index].z, faceUV[index].y);
  31076. if (faceColors) {
  31077. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31078. }
  31079. }
  31080. // sides
  31081. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31082. // Result
  31083. var vertexData = new VertexData();
  31084. vertexData.indices = indices;
  31085. vertexData.positions = positions;
  31086. vertexData.normals = normals;
  31087. vertexData.uvs = uvs;
  31088. if (faceColors) {
  31089. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31090. vertexData.colors = totalColors;
  31091. }
  31092. return vertexData;
  31093. };
  31094. /**
  31095. * Creates the VertexData of the Sphere.
  31096. */
  31097. VertexData.CreateSphere = function (options) {
  31098. var segments = options.segments || 32;
  31099. var diameterX = options.diameterX || options.diameter || 1;
  31100. var diameterY = options.diameterY || options.diameter || 1;
  31101. var diameterZ = options.diameterZ || options.diameter || 1;
  31102. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31103. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31104. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31105. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31106. var totalZRotationSteps = 2 + segments;
  31107. var totalYRotationSteps = 2 * totalZRotationSteps;
  31108. var indices = [];
  31109. var positions = [];
  31110. var normals = [];
  31111. var uvs = [];
  31112. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31113. var normalizedZ = zRotationStep / totalZRotationSteps;
  31114. var angleZ = normalizedZ * Math.PI * slice;
  31115. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31116. var normalizedY = yRotationStep / totalYRotationSteps;
  31117. var angleY = normalizedY * Math.PI * 2 * arc;
  31118. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31119. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31120. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31121. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31122. var vertex = complete.multiply(radius);
  31123. var normal = complete.divide(radius).normalize();
  31124. positions.push(vertex.x, vertex.y, vertex.z);
  31125. normals.push(normal.x, normal.y, normal.z);
  31126. uvs.push(normalizedY, normalizedZ);
  31127. }
  31128. if (zRotationStep > 0) {
  31129. var verticesCount = positions.length / 3;
  31130. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31131. indices.push((firstIndex));
  31132. indices.push((firstIndex + 1));
  31133. indices.push(firstIndex + totalYRotationSteps + 1);
  31134. indices.push((firstIndex + totalYRotationSteps + 1));
  31135. indices.push((firstIndex + 1));
  31136. indices.push((firstIndex + totalYRotationSteps + 2));
  31137. }
  31138. }
  31139. }
  31140. // Sides
  31141. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31142. // Result
  31143. var vertexData = new VertexData();
  31144. vertexData.indices = indices;
  31145. vertexData.positions = positions;
  31146. vertexData.normals = normals;
  31147. vertexData.uvs = uvs;
  31148. return vertexData;
  31149. };
  31150. /**
  31151. * Creates the VertexData of the Cylinder or Cone.
  31152. */
  31153. VertexData.CreateCylinder = function (options) {
  31154. var height = options.height || 2;
  31155. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31156. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31157. var tessellation = options.tessellation || 24;
  31158. var subdivisions = options.subdivisions || 1;
  31159. var hasRings = options.hasRings ? true : false;
  31160. var enclose = options.enclose ? true : false;
  31161. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31162. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31163. var faceUV = options.faceUV || new Array(3);
  31164. var faceColors = options.faceColors;
  31165. // default face colors and UV if undefined
  31166. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31167. var ringNb = (hasRings) ? subdivisions : 1;
  31168. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31169. var f;
  31170. for (f = 0; f < surfaceNb; f++) {
  31171. if (faceColors && faceColors[f] === undefined) {
  31172. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31173. }
  31174. }
  31175. for (f = 0; f < surfaceNb; f++) {
  31176. if (faceUV && faceUV[f] === undefined) {
  31177. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31178. }
  31179. }
  31180. var indices = new Array();
  31181. var positions = new Array();
  31182. var normals = new Array();
  31183. var uvs = new Array();
  31184. var colors = new Array();
  31185. var angle_step = Math.PI * 2 * arc / tessellation;
  31186. var angle;
  31187. var h;
  31188. var radius;
  31189. var tan = (diameterBottom - diameterTop) / 2 / height;
  31190. var ringVertex = BABYLON.Vector3.Zero();
  31191. var ringNormal = BABYLON.Vector3.Zero();
  31192. var ringFirstVertex = BABYLON.Vector3.Zero();
  31193. var ringFirstNormal = BABYLON.Vector3.Zero();
  31194. var quadNormal = BABYLON.Vector3.Zero();
  31195. var Y = BABYLON.Axis.Y;
  31196. // positions, normals, uvs
  31197. var i;
  31198. var j;
  31199. var r;
  31200. var ringIdx = 1;
  31201. var s = 1; // surface index
  31202. var cs = 0;
  31203. var v = 0;
  31204. for (i = 0; i <= subdivisions; i++) {
  31205. h = i / subdivisions;
  31206. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31207. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31208. for (r = 0; r < ringIdx; r++) {
  31209. if (hasRings) {
  31210. s += r;
  31211. }
  31212. if (enclose) {
  31213. s += 2 * r;
  31214. }
  31215. for (j = 0; j <= tessellation; j++) {
  31216. angle = j * angle_step;
  31217. // position
  31218. ringVertex.x = Math.cos(-angle) * radius;
  31219. ringVertex.y = -height / 2 + h * height;
  31220. ringVertex.z = Math.sin(-angle) * radius;
  31221. // normal
  31222. if (diameterTop === 0 && i === subdivisions) {
  31223. // if no top cap, reuse former normals
  31224. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31225. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31226. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31227. }
  31228. else {
  31229. ringNormal.x = ringVertex.x;
  31230. ringNormal.z = ringVertex.z;
  31231. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31232. ringNormal.normalize();
  31233. }
  31234. // keep first ring vertex values for enclose
  31235. if (j === 0) {
  31236. ringFirstVertex.copyFrom(ringVertex);
  31237. ringFirstNormal.copyFrom(ringNormal);
  31238. }
  31239. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31240. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31241. if (hasRings) {
  31242. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31243. }
  31244. else {
  31245. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31246. }
  31247. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31248. if (faceColors) {
  31249. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31250. }
  31251. }
  31252. // if enclose, add four vertices and their dedicated normals
  31253. if (arc !== 1 && enclose) {
  31254. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31255. positions.push(0, ringVertex.y, 0);
  31256. positions.push(0, ringVertex.y, 0);
  31257. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31258. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31259. quadNormal.normalize();
  31260. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31261. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31262. quadNormal.normalize();
  31263. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31264. if (hasRings) {
  31265. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31266. }
  31267. else {
  31268. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31269. }
  31270. uvs.push(faceUV[s + 1].x, v);
  31271. uvs.push(faceUV[s + 1].z, v);
  31272. if (hasRings) {
  31273. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31274. }
  31275. else {
  31276. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31277. }
  31278. uvs.push(faceUV[s + 2].x, v);
  31279. uvs.push(faceUV[s + 2].z, v);
  31280. if (faceColors) {
  31281. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31282. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31283. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31284. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31285. }
  31286. }
  31287. if (cs !== s) {
  31288. cs = s;
  31289. }
  31290. }
  31291. }
  31292. // indices
  31293. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31294. var s;
  31295. i = 0;
  31296. for (s = 0; s < subdivisions; s++) {
  31297. var i0 = 0;
  31298. var i1 = 0;
  31299. var i2 = 0;
  31300. var i3 = 0;
  31301. for (j = 0; j < tessellation; j++) {
  31302. i0 = i * (e + 1) + j;
  31303. i1 = (i + 1) * (e + 1) + j;
  31304. i2 = i * (e + 1) + (j + 1);
  31305. i3 = (i + 1) * (e + 1) + (j + 1);
  31306. indices.push(i0, i1, i2);
  31307. indices.push(i3, i2, i1);
  31308. }
  31309. if (arc !== 1 && enclose) {
  31310. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31311. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31312. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31313. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31314. }
  31315. i = (hasRings) ? (i + 2) : (i + 1);
  31316. }
  31317. // Caps
  31318. var createCylinderCap = function (isTop) {
  31319. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31320. if (radius === 0) {
  31321. return;
  31322. }
  31323. // Cap positions, normals & uvs
  31324. var angle;
  31325. var circleVector;
  31326. var i;
  31327. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31328. var c = null;
  31329. if (faceColors) {
  31330. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31331. }
  31332. // cap center
  31333. var vbase = positions.length / 3;
  31334. var offset = isTop ? height / 2 : -height / 2;
  31335. var center = new BABYLON.Vector3(0, offset, 0);
  31336. positions.push(center.x, center.y, center.z);
  31337. normals.push(0, isTop ? 1 : -1, 0);
  31338. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31339. if (c) {
  31340. colors.push(c.r, c.g, c.b, c.a);
  31341. }
  31342. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31343. for (i = 0; i <= tessellation; i++) {
  31344. angle = Math.PI * 2 * i * arc / tessellation;
  31345. var cos = Math.cos(-angle);
  31346. var sin = Math.sin(-angle);
  31347. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31348. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31349. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31350. normals.push(0, isTop ? 1 : -1, 0);
  31351. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31352. if (c) {
  31353. colors.push(c.r, c.g, c.b, c.a);
  31354. }
  31355. }
  31356. // Cap indices
  31357. for (i = 0; i < tessellation; i++) {
  31358. if (!isTop) {
  31359. indices.push(vbase);
  31360. indices.push(vbase + (i + 1));
  31361. indices.push(vbase + (i + 2));
  31362. }
  31363. else {
  31364. indices.push(vbase);
  31365. indices.push(vbase + (i + 2));
  31366. indices.push(vbase + (i + 1));
  31367. }
  31368. }
  31369. };
  31370. // add caps to geometry
  31371. createCylinderCap(false);
  31372. createCylinderCap(true);
  31373. // Sides
  31374. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31375. var vertexData = new VertexData();
  31376. vertexData.indices = indices;
  31377. vertexData.positions = positions;
  31378. vertexData.normals = normals;
  31379. vertexData.uvs = uvs;
  31380. if (faceColors) {
  31381. vertexData.colors = colors;
  31382. }
  31383. return vertexData;
  31384. };
  31385. /**
  31386. * Creates the VertexData of the Torus.
  31387. */
  31388. VertexData.CreateTorus = function (options) {
  31389. var indices = [];
  31390. var positions = [];
  31391. var normals = [];
  31392. var uvs = [];
  31393. var diameter = options.diameter || 1;
  31394. var thickness = options.thickness || 0.5;
  31395. var tessellation = options.tessellation || 16;
  31396. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31397. var stride = tessellation + 1;
  31398. for (var i = 0; i <= tessellation; i++) {
  31399. var u = i / tessellation;
  31400. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31401. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31402. for (var j = 0; j <= tessellation; j++) {
  31403. var v = 1 - j / tessellation;
  31404. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31405. var dx = Math.cos(innerAngle);
  31406. var dy = Math.sin(innerAngle);
  31407. // Create a vertex.
  31408. var normal = new BABYLON.Vector3(dx, dy, 0);
  31409. var position = normal.scale(thickness / 2);
  31410. var textureCoordinate = new BABYLON.Vector2(u, v);
  31411. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31412. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31413. positions.push(position.x, position.y, position.z);
  31414. normals.push(normal.x, normal.y, normal.z);
  31415. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31416. // And create indices for two triangles.
  31417. var nextI = (i + 1) % stride;
  31418. var nextJ = (j + 1) % stride;
  31419. indices.push(i * stride + j);
  31420. indices.push(i * stride + nextJ);
  31421. indices.push(nextI * stride + j);
  31422. indices.push(i * stride + nextJ);
  31423. indices.push(nextI * stride + nextJ);
  31424. indices.push(nextI * stride + j);
  31425. }
  31426. }
  31427. // Sides
  31428. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31429. // Result
  31430. var vertexData = new VertexData();
  31431. vertexData.indices = indices;
  31432. vertexData.positions = positions;
  31433. vertexData.normals = normals;
  31434. vertexData.uvs = uvs;
  31435. return vertexData;
  31436. };
  31437. /**
  31438. * Creates the VertexData of the LineSystem.
  31439. */
  31440. VertexData.CreateLineSystem = function (options) {
  31441. var indices = [];
  31442. var positions = [];
  31443. var lines = options.lines;
  31444. var colors = options.colors;
  31445. var vertexColors = [];
  31446. var idx = 0;
  31447. for (var l = 0; l < lines.length; l++) {
  31448. var points = lines[l];
  31449. for (var index = 0; index < points.length; index++) {
  31450. positions.push(points[index].x, points[index].y, points[index].z);
  31451. if (colors) {
  31452. var color = colors[l];
  31453. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31454. }
  31455. if (index > 0) {
  31456. indices.push(idx - 1);
  31457. indices.push(idx);
  31458. }
  31459. idx++;
  31460. }
  31461. }
  31462. var vertexData = new VertexData();
  31463. vertexData.indices = indices;
  31464. vertexData.positions = positions;
  31465. if (colors) {
  31466. vertexData.colors = vertexColors;
  31467. }
  31468. return vertexData;
  31469. };
  31470. /**
  31471. * Create the VertexData of the DashedLines.
  31472. */
  31473. VertexData.CreateDashedLines = function (options) {
  31474. var dashSize = options.dashSize || 3;
  31475. var gapSize = options.gapSize || 1;
  31476. var dashNb = options.dashNb || 200;
  31477. var points = options.points;
  31478. var positions = new Array();
  31479. var indices = new Array();
  31480. var curvect = BABYLON.Vector3.Zero();
  31481. var lg = 0;
  31482. var nb = 0;
  31483. var shft = 0;
  31484. var dashshft = 0;
  31485. var curshft = 0;
  31486. var idx = 0;
  31487. var i = 0;
  31488. for (i = 0; i < points.length - 1; i++) {
  31489. points[i + 1].subtractToRef(points[i], curvect);
  31490. lg += curvect.length();
  31491. }
  31492. shft = lg / dashNb;
  31493. dashshft = dashSize * shft / (dashSize + gapSize);
  31494. for (i = 0; i < points.length - 1; i++) {
  31495. points[i + 1].subtractToRef(points[i], curvect);
  31496. nb = Math.floor(curvect.length() / shft);
  31497. curvect.normalize();
  31498. for (var j = 0; j < nb; j++) {
  31499. curshft = shft * j;
  31500. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31501. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31502. indices.push(idx, idx + 1);
  31503. idx += 2;
  31504. }
  31505. }
  31506. // Result
  31507. var vertexData = new VertexData();
  31508. vertexData.positions = positions;
  31509. vertexData.indices = indices;
  31510. return vertexData;
  31511. };
  31512. /**
  31513. * Creates the VertexData of the Ground.
  31514. */
  31515. VertexData.CreateGround = function (options) {
  31516. var indices = [];
  31517. var positions = [];
  31518. var normals = [];
  31519. var uvs = [];
  31520. var row, col;
  31521. var width = options.width || 1;
  31522. var height = options.height || 1;
  31523. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31524. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31525. for (row = 0; row <= subdivisionsY; row++) {
  31526. for (col = 0; col <= subdivisionsX; col++) {
  31527. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31528. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31529. positions.push(position.x, position.y, position.z);
  31530. normals.push(normal.x, normal.y, normal.z);
  31531. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31532. }
  31533. }
  31534. for (row = 0; row < subdivisionsY; row++) {
  31535. for (col = 0; col < subdivisionsX; col++) {
  31536. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31537. indices.push(col + 1 + row * (subdivisionsX + 1));
  31538. indices.push(col + row * (subdivisionsX + 1));
  31539. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31540. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31541. indices.push(col + row * (subdivisionsX + 1));
  31542. }
  31543. }
  31544. // Result
  31545. var vertexData = new VertexData();
  31546. vertexData.indices = indices;
  31547. vertexData.positions = positions;
  31548. vertexData.normals = normals;
  31549. vertexData.uvs = uvs;
  31550. return vertexData;
  31551. };
  31552. /**
  31553. * Creates the VertexData of the TiledGround.
  31554. */
  31555. VertexData.CreateTiledGround = function (options) {
  31556. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31557. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31558. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31559. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31560. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31561. var precision = options.precision || { w: 1, h: 1 };
  31562. var indices = new Array();
  31563. var positions = new Array();
  31564. var normals = new Array();
  31565. var uvs = new Array();
  31566. var row, col, tileRow, tileCol;
  31567. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31568. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31569. precision.w = (precision.w < 1) ? 1 : precision.w;
  31570. precision.h = (precision.h < 1) ? 1 : precision.h;
  31571. var tileSize = {
  31572. 'w': (xmax - xmin) / subdivisions.w,
  31573. 'h': (zmax - zmin) / subdivisions.h
  31574. };
  31575. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31576. // Indices
  31577. var base = positions.length / 3;
  31578. var rowLength = precision.w + 1;
  31579. for (row = 0; row < precision.h; row++) {
  31580. for (col = 0; col < precision.w; col++) {
  31581. var square = [
  31582. base + col + row * rowLength,
  31583. base + (col + 1) + row * rowLength,
  31584. base + (col + 1) + (row + 1) * rowLength,
  31585. base + col + (row + 1) * rowLength
  31586. ];
  31587. indices.push(square[1]);
  31588. indices.push(square[2]);
  31589. indices.push(square[3]);
  31590. indices.push(square[0]);
  31591. indices.push(square[1]);
  31592. indices.push(square[3]);
  31593. }
  31594. }
  31595. // Position, normals and uvs
  31596. var position = BABYLON.Vector3.Zero();
  31597. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31598. for (row = 0; row <= precision.h; row++) {
  31599. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31600. for (col = 0; col <= precision.w; col++) {
  31601. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31602. position.y = 0;
  31603. positions.push(position.x, position.y, position.z);
  31604. normals.push(normal.x, normal.y, normal.z);
  31605. uvs.push(col / precision.w, row / precision.h);
  31606. }
  31607. }
  31608. }
  31609. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31610. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31611. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31612. }
  31613. }
  31614. // Result
  31615. var vertexData = new VertexData();
  31616. vertexData.indices = indices;
  31617. vertexData.positions = positions;
  31618. vertexData.normals = normals;
  31619. vertexData.uvs = uvs;
  31620. return vertexData;
  31621. };
  31622. /**
  31623. * Creates the VertexData of the Ground designed from a heightmap.
  31624. */
  31625. VertexData.CreateGroundFromHeightMap = function (options) {
  31626. var indices = [];
  31627. var positions = [];
  31628. var normals = [];
  31629. var uvs = [];
  31630. var row, col;
  31631. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31632. // Vertices
  31633. for (row = 0; row <= options.subdivisions; row++) {
  31634. for (col = 0; col <= options.subdivisions; col++) {
  31635. 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));
  31636. // Compute height
  31637. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31638. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31639. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31640. var r = options.buffer[pos] / 255.0;
  31641. var g = options.buffer[pos + 1] / 255.0;
  31642. var b = options.buffer[pos + 2] / 255.0;
  31643. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31644. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31645. // Add vertex
  31646. positions.push(position.x, position.y, position.z);
  31647. normals.push(0, 0, 0);
  31648. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31649. }
  31650. }
  31651. // Indices
  31652. for (row = 0; row < options.subdivisions; row++) {
  31653. for (col = 0; col < options.subdivisions; col++) {
  31654. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31655. indices.push(col + 1 + row * (options.subdivisions + 1));
  31656. indices.push(col + row * (options.subdivisions + 1));
  31657. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31658. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31659. indices.push(col + row * (options.subdivisions + 1));
  31660. }
  31661. }
  31662. // Normals
  31663. VertexData.ComputeNormals(positions, indices, normals);
  31664. // Result
  31665. var vertexData = new VertexData();
  31666. vertexData.indices = indices;
  31667. vertexData.positions = positions;
  31668. vertexData.normals = normals;
  31669. vertexData.uvs = uvs;
  31670. return vertexData;
  31671. };
  31672. /**
  31673. * Creates the VertexData of the Plane.
  31674. */
  31675. VertexData.CreatePlane = function (options) {
  31676. var indices = [];
  31677. var positions = [];
  31678. var normals = [];
  31679. var uvs = [];
  31680. var width = options.width || options.size || 1;
  31681. var height = options.height || options.size || 1;
  31682. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31683. // Vertices
  31684. var halfWidth = width / 2.0;
  31685. var halfHeight = height / 2.0;
  31686. positions.push(-halfWidth, -halfHeight, 0);
  31687. normals.push(0, 0, -1.0);
  31688. uvs.push(0.0, 0.0);
  31689. positions.push(halfWidth, -halfHeight, 0);
  31690. normals.push(0, 0, -1.0);
  31691. uvs.push(1.0, 0.0);
  31692. positions.push(halfWidth, halfHeight, 0);
  31693. normals.push(0, 0, -1.0);
  31694. uvs.push(1.0, 1.0);
  31695. positions.push(-halfWidth, halfHeight, 0);
  31696. normals.push(0, 0, -1.0);
  31697. uvs.push(0.0, 1.0);
  31698. // Indices
  31699. indices.push(0);
  31700. indices.push(1);
  31701. indices.push(2);
  31702. indices.push(0);
  31703. indices.push(2);
  31704. indices.push(3);
  31705. // Sides
  31706. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31707. // Result
  31708. var vertexData = new VertexData();
  31709. vertexData.indices = indices;
  31710. vertexData.positions = positions;
  31711. vertexData.normals = normals;
  31712. vertexData.uvs = uvs;
  31713. return vertexData;
  31714. };
  31715. /**
  31716. * Creates the VertexData of the Disc or regular Polygon.
  31717. */
  31718. VertexData.CreateDisc = function (options) {
  31719. var positions = new Array();
  31720. var indices = new Array();
  31721. var normals = new Array();
  31722. var uvs = new Array();
  31723. var radius = options.radius || 0.5;
  31724. var tessellation = options.tessellation || 64;
  31725. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31726. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31727. // positions and uvs
  31728. positions.push(0, 0, 0); // disc center first
  31729. uvs.push(0.5, 0.5);
  31730. var theta = Math.PI * 2 * arc;
  31731. var step = theta / tessellation;
  31732. for (var a = 0; a < theta; a += step) {
  31733. var x = Math.cos(a);
  31734. var y = Math.sin(a);
  31735. var u = (x + 1) / 2;
  31736. var v = (1 - y) / 2;
  31737. positions.push(radius * x, radius * y, 0);
  31738. uvs.push(u, v);
  31739. }
  31740. if (arc === 1) {
  31741. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31742. uvs.push(uvs[2], uvs[3]);
  31743. }
  31744. //indices
  31745. var vertexNb = positions.length / 3;
  31746. for (var i = 1; i < vertexNb - 1; i++) {
  31747. indices.push(i + 1, 0, i);
  31748. }
  31749. // result
  31750. VertexData.ComputeNormals(positions, indices, normals);
  31751. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31752. var vertexData = new VertexData();
  31753. vertexData.indices = indices;
  31754. vertexData.positions = positions;
  31755. vertexData.normals = normals;
  31756. vertexData.uvs = uvs;
  31757. return vertexData;
  31758. };
  31759. /**
  31760. * Re-creates the VertexData of the Polygon for sideOrientation.
  31761. */
  31762. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31763. var faceUV = fUV || new Array(3);
  31764. var faceColors = fColors;
  31765. var colors = [];
  31766. // default face colors and UV if undefined
  31767. for (var f = 0; f < 3; f++) {
  31768. if (faceUV[f] === undefined) {
  31769. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31770. }
  31771. if (faceColors && faceColors[f] === undefined) {
  31772. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31773. }
  31774. }
  31775. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31776. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31777. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31778. var indices = polygon.getIndices();
  31779. // set face colours and textures
  31780. var idx = 0;
  31781. var face = 0;
  31782. for (var index = 0; index < normals.length; index += 3) {
  31783. //Edge Face no. 1
  31784. if (Math.abs(normals[index + 1]) < 0.001) {
  31785. face = 1;
  31786. }
  31787. //Top Face no. 0
  31788. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31789. face = 0;
  31790. }
  31791. //Bottom Face no. 2
  31792. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31793. face = 2;
  31794. }
  31795. idx = index / 3;
  31796. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31797. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31798. if (faceColors) {
  31799. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31800. }
  31801. }
  31802. // sides
  31803. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31804. // Result
  31805. var vertexData = new VertexData();
  31806. vertexData.indices = indices;
  31807. vertexData.positions = positions;
  31808. vertexData.normals = normals;
  31809. vertexData.uvs = uvs;
  31810. if (faceColors) {
  31811. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31812. vertexData.colors = totalColors;
  31813. }
  31814. return vertexData;
  31815. };
  31816. /**
  31817. * Creates the VertexData of the IcoSphere.
  31818. */
  31819. VertexData.CreateIcoSphere = function (options) {
  31820. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31821. var radius = options.radius || 1;
  31822. var flat = (options.flat === undefined) ? true : options.flat;
  31823. var subdivisions = options.subdivisions || 4;
  31824. var radiusX = options.radiusX || radius;
  31825. var radiusY = options.radiusY || radius;
  31826. var radiusZ = options.radiusZ || radius;
  31827. var t = (1 + Math.sqrt(5)) / 2;
  31828. // 12 vertex x,y,z
  31829. var ico_vertices = [
  31830. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31831. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31832. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31833. ];
  31834. // index of 3 vertex makes a face of icopshere
  31835. var ico_indices = [
  31836. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31837. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31838. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31839. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31840. ];
  31841. // vertex for uv have aliased position, not for UV
  31842. var vertices_unalias_id = [
  31843. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31844. // vertex alias
  31845. 0,
  31846. 2,
  31847. 3,
  31848. 3,
  31849. 3,
  31850. 4,
  31851. 7,
  31852. 8,
  31853. 9,
  31854. 9,
  31855. 10,
  31856. 11 // 23: B + 12
  31857. ];
  31858. // uv as integer step (not pixels !)
  31859. var ico_vertexuv = [
  31860. 5, 1, 3, 1, 6, 4, 0, 0,
  31861. 5, 3, 4, 2, 2, 2, 4, 0,
  31862. 2, 0, 1, 1, 6, 0, 6, 2,
  31863. // vertex alias (for same vertex on different faces)
  31864. 0, 4,
  31865. 3, 3,
  31866. 4, 4,
  31867. 3, 1,
  31868. 4, 2,
  31869. 4, 4,
  31870. 0, 2,
  31871. 1, 1,
  31872. 2, 2,
  31873. 3, 3,
  31874. 1, 3,
  31875. 2, 4 // 23: B + 12
  31876. ];
  31877. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31878. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31879. // First island of uv mapping
  31880. // v = 4h 3+ 2
  31881. // v = 3h 9+ 4
  31882. // v = 2h 9+ 5 B
  31883. // v = 1h 9 1 0
  31884. // v = 0h 3 8 7 A
  31885. // u = 0 1 2 3 4 5 6 *a
  31886. // Second island of uv mapping
  31887. // v = 4h 0+ B+ 4+
  31888. // v = 3h A+ 2+
  31889. // v = 2h 7+ 6 3+
  31890. // v = 1h 8+ 3+
  31891. // v = 0h
  31892. // u = 0 1 2 3 4 5 6 *a
  31893. // Face layout on texture UV mapping
  31894. // ============
  31895. // \ 4 /\ 16 / ======
  31896. // \ / \ / /\ 11 /
  31897. // \/ 7 \/ / \ /
  31898. // ======= / 10 \/
  31899. // /\ 17 /\ =======
  31900. // / \ / \ \ 15 /\
  31901. // / 8 \/ 12 \ \ / \
  31902. // ============ \/ 6 \
  31903. // \ 18 /\ ============
  31904. // \ / \ \ 5 /\ 0 /
  31905. // \/ 13 \ \ / \ /
  31906. // ======= \/ 1 \/
  31907. // =============
  31908. // /\ 19 /\ 2 /\
  31909. // / \ / \ / \
  31910. // / 14 \/ 9 \/ 3 \
  31911. // ===================
  31912. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31913. var ustep = 138 / 1024;
  31914. var vstep = 239 / 1024;
  31915. var uoffset = 60 / 1024;
  31916. var voffset = 26 / 1024;
  31917. // Second island should have margin, not to touch the first island
  31918. // avoid any borderline artefact in pixel rounding
  31919. var island_u_offset = -40 / 1024;
  31920. var island_v_offset = +20 / 1024;
  31921. // face is either island 0 or 1 :
  31922. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31923. var island = [
  31924. 0, 0, 0, 0, 1,
  31925. 0, 0, 1, 1, 0,
  31926. 0, 0, 1, 1, 0,
  31927. 0, 1, 1, 1, 0 // 15 - 19
  31928. ];
  31929. var indices = new Array();
  31930. var positions = new Array();
  31931. var normals = new Array();
  31932. var uvs = new Array();
  31933. var current_indice = 0;
  31934. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31935. var face_vertex_pos = new Array(3);
  31936. var face_vertex_uv = new Array(3);
  31937. var v012;
  31938. for (v012 = 0; v012 < 3; v012++) {
  31939. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31940. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31941. }
  31942. // create all with normals
  31943. for (var face = 0; face < 20; face++) {
  31944. // 3 vertex per face
  31945. for (v012 = 0; v012 < 3; v012++) {
  31946. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31947. var v_id = ico_indices[3 * face + v012];
  31948. // vertex have 3D position (x,y,z)
  31949. 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]);
  31950. // Normalize to get normal, then scale to radius
  31951. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31952. // uv Coordinates from vertex ID
  31953. 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);
  31954. }
  31955. // Subdivide the face (interpolate pos, norm, uv)
  31956. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31957. // - norm is linear interpolation of vertex corner normal
  31958. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31959. // - uv is linear interpolation
  31960. //
  31961. // Topology is as below for sub-divide by 2
  31962. // vertex shown as v0,v1,v2
  31963. // interp index is i1 to progress in range [v0,v1[
  31964. // interp index is i2 to progress in range [v0,v2[
  31965. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31966. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31967. //
  31968. //
  31969. // i2 v2
  31970. // ^ ^
  31971. // / / \
  31972. // / / \
  31973. // / / \
  31974. // / / (0,1) \
  31975. // / #---------\
  31976. // / / \ (0,0)'/ \
  31977. // / / \ / \
  31978. // / / \ / \
  31979. // / / (0,0) \ / (1,0) \
  31980. // / #---------#---------\
  31981. // v0 v1
  31982. //
  31983. // --------------------> i1
  31984. //
  31985. // interp of (i1,i2):
  31986. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31987. // along i1 : lerp(x0,x1, i1/(S-i2))
  31988. //
  31989. // centroid of triangle is needed to get help normal computation
  31990. // (c1,c2) are used for centroid location
  31991. var interp_vertex = function (i1, i2, c1, c2) {
  31992. // vertex is interpolated from
  31993. // - face_vertex_pos[0..2]
  31994. // - face_vertex_uv[0..2]
  31995. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31996. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31997. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31998. pos_interp.normalize();
  31999. var vertex_normal;
  32000. if (flat) {
  32001. // in flat mode, recalculate normal as face centroid normal
  32002. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32003. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32004. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32005. }
  32006. else {
  32007. // in smooth mode, recalculate normal from each single vertex position
  32008. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32009. }
  32010. // Vertex normal need correction due to X,Y,Z radius scaling
  32011. vertex_normal.x /= radiusX;
  32012. vertex_normal.y /= radiusY;
  32013. vertex_normal.z /= radiusZ;
  32014. vertex_normal.normalize();
  32015. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32016. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32017. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32018. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32019. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32020. uvs.push(uv_interp.x, uv_interp.y);
  32021. // push each vertex has member of a face
  32022. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32023. indices.push(current_indice);
  32024. current_indice++;
  32025. };
  32026. for (var i2 = 0; i2 < subdivisions; i2++) {
  32027. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32028. // face : (i1,i2) for /\ :
  32029. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32030. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32031. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32032. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32033. if (i1 + i2 + 1 < subdivisions) {
  32034. // face : (i1,i2)' for \/ :
  32035. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32036. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32037. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32038. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32039. }
  32040. }
  32041. }
  32042. }
  32043. // Sides
  32044. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32045. // Result
  32046. var vertexData = new VertexData();
  32047. vertexData.indices = indices;
  32048. vertexData.positions = positions;
  32049. vertexData.normals = normals;
  32050. vertexData.uvs = uvs;
  32051. return vertexData;
  32052. };
  32053. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32054. /**
  32055. * Creates the VertexData of the Polyhedron.
  32056. */
  32057. VertexData.CreatePolyhedron = function (options) {
  32058. // provided polyhedron types :
  32059. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32060. // 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)
  32061. var polyhedra = [];
  32062. 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]] };
  32063. 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]] };
  32064. polyhedra[2] = {
  32065. 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]],
  32066. 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]]
  32067. };
  32068. polyhedra[3] = {
  32069. 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]],
  32070. 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]]
  32071. };
  32072. polyhedra[4] = {
  32073. 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]],
  32074. 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]]
  32075. };
  32076. 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]] };
  32077. 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]] };
  32078. 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]] };
  32079. 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]] };
  32080. 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]] };
  32081. 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]] };
  32082. 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]] };
  32083. 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]] };
  32084. 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]] };
  32085. polyhedra[14] = {
  32086. 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]],
  32087. 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]]
  32088. };
  32089. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32090. var size = options.size;
  32091. var sizeX = options.sizeX || size || 1;
  32092. var sizeY = options.sizeY || size || 1;
  32093. var sizeZ = options.sizeZ || size || 1;
  32094. var data = options.custom || polyhedra[type];
  32095. var nbfaces = data.face.length;
  32096. var faceUV = options.faceUV || new Array(nbfaces);
  32097. var faceColors = options.faceColors;
  32098. var flat = (options.flat === undefined) ? true : options.flat;
  32099. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32100. var positions = new Array();
  32101. var indices = new Array();
  32102. var normals = new Array();
  32103. var uvs = new Array();
  32104. var colors = new Array();
  32105. var index = 0;
  32106. var faceIdx = 0; // face cursor in the array "indexes"
  32107. var indexes = new Array();
  32108. var i = 0;
  32109. var f = 0;
  32110. var u, v, ang, x, y, tmp;
  32111. // default face colors and UV if undefined
  32112. if (flat) {
  32113. for (f = 0; f < nbfaces; f++) {
  32114. if (faceColors && faceColors[f] === undefined) {
  32115. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32116. }
  32117. if (faceUV && faceUV[f] === undefined) {
  32118. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32119. }
  32120. }
  32121. }
  32122. if (!flat) {
  32123. for (i = 0; i < data.vertex.length; i++) {
  32124. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32125. uvs.push(0, 0);
  32126. }
  32127. for (f = 0; f < nbfaces; f++) {
  32128. for (i = 0; i < data.face[f].length - 2; i++) {
  32129. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32130. }
  32131. }
  32132. }
  32133. else {
  32134. for (f = 0; f < nbfaces; f++) {
  32135. var fl = data.face[f].length; // number of vertices of the current face
  32136. ang = 2 * Math.PI / fl;
  32137. x = 0.5 * Math.tan(ang / 2);
  32138. y = 0.5;
  32139. // positions, uvs, colors
  32140. for (i = 0; i < fl; i++) {
  32141. // positions
  32142. 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);
  32143. indexes.push(index);
  32144. index++;
  32145. // uvs
  32146. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32147. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32148. uvs.push(u, v);
  32149. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32150. y = x * Math.sin(ang) + y * Math.cos(ang);
  32151. x = tmp;
  32152. // colors
  32153. if (faceColors) {
  32154. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32155. }
  32156. }
  32157. // indices from indexes
  32158. for (i = 0; i < fl - 2; i++) {
  32159. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32160. }
  32161. faceIdx += fl;
  32162. }
  32163. }
  32164. VertexData.ComputeNormals(positions, indices, normals);
  32165. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32166. var vertexData = new VertexData();
  32167. vertexData.positions = positions;
  32168. vertexData.indices = indices;
  32169. vertexData.normals = normals;
  32170. vertexData.uvs = uvs;
  32171. if (faceColors && flat) {
  32172. vertexData.colors = colors;
  32173. }
  32174. return vertexData;
  32175. };
  32176. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32177. /**
  32178. * Creates the VertexData of the Torus Knot.
  32179. */
  32180. VertexData.CreateTorusKnot = function (options) {
  32181. var indices = new Array();
  32182. var positions = new Array();
  32183. var normals = new Array();
  32184. var uvs = new Array();
  32185. var radius = options.radius || 2;
  32186. var tube = options.tube || 0.5;
  32187. var radialSegments = options.radialSegments || 32;
  32188. var tubularSegments = options.tubularSegments || 32;
  32189. var p = options.p || 2;
  32190. var q = options.q || 3;
  32191. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32192. // Helper
  32193. var getPos = function (angle) {
  32194. var cu = Math.cos(angle);
  32195. var su = Math.sin(angle);
  32196. var quOverP = q / p * angle;
  32197. var cs = Math.cos(quOverP);
  32198. var tx = radius * (2 + cs) * 0.5 * cu;
  32199. var ty = radius * (2 + cs) * su * 0.5;
  32200. var tz = radius * Math.sin(quOverP) * 0.5;
  32201. return new BABYLON.Vector3(tx, ty, tz);
  32202. };
  32203. // Vertices
  32204. var i;
  32205. var j;
  32206. for (i = 0; i <= radialSegments; i++) {
  32207. var modI = i % radialSegments;
  32208. var u = modI / radialSegments * 2 * p * Math.PI;
  32209. var p1 = getPos(u);
  32210. var p2 = getPos(u + 0.01);
  32211. var tang = p2.subtract(p1);
  32212. var n = p2.add(p1);
  32213. var bitan = BABYLON.Vector3.Cross(tang, n);
  32214. n = BABYLON.Vector3.Cross(bitan, tang);
  32215. bitan.normalize();
  32216. n.normalize();
  32217. for (j = 0; j < tubularSegments; j++) {
  32218. var modJ = j % tubularSegments;
  32219. var v = modJ / tubularSegments * 2 * Math.PI;
  32220. var cx = -tube * Math.cos(v);
  32221. var cy = tube * Math.sin(v);
  32222. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32223. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32224. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32225. uvs.push(i / radialSegments);
  32226. uvs.push(j / tubularSegments);
  32227. }
  32228. }
  32229. for (i = 0; i < radialSegments; i++) {
  32230. for (j = 0; j < tubularSegments; j++) {
  32231. var jNext = (j + 1) % tubularSegments;
  32232. var a = i * tubularSegments + j;
  32233. var b = (i + 1) * tubularSegments + j;
  32234. var c = (i + 1) * tubularSegments + jNext;
  32235. var d = i * tubularSegments + jNext;
  32236. indices.push(d);
  32237. indices.push(b);
  32238. indices.push(a);
  32239. indices.push(d);
  32240. indices.push(c);
  32241. indices.push(b);
  32242. }
  32243. }
  32244. // Normals
  32245. VertexData.ComputeNormals(positions, indices, normals);
  32246. // Sides
  32247. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32248. // Result
  32249. var vertexData = new VertexData();
  32250. vertexData.indices = indices;
  32251. vertexData.positions = positions;
  32252. vertexData.normals = normals;
  32253. vertexData.uvs = uvs;
  32254. return vertexData;
  32255. };
  32256. // Tools
  32257. /**
  32258. * @param {any} - positions (number[] or Float32Array)
  32259. * @param {any} - indices (number[] or Uint16Array)
  32260. * @param {any} - normals (number[] or Float32Array)
  32261. * options (optional) :
  32262. * facetPositions : optional array of facet positions (vector3)
  32263. * facetNormals : optional array of facet normals (vector3)
  32264. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32265. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32266. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32267. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32268. * bInfo : optional bounding info, required for facetPartitioning computation
  32269. * useRightHandedSystem: optional boolean to for right handed system computation
  32270. * depthSort : optional boolean to enable the facet depth sort computation
  32271. * distanceTo : optional Vector3 to compute the facet depth from this location
  32272. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32273. */
  32274. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32275. // temporary scalar variables
  32276. var index = 0; // facet index
  32277. var p1p2x = 0.0; // p1p2 vector x coordinate
  32278. var p1p2y = 0.0; // p1p2 vector y coordinate
  32279. var p1p2z = 0.0; // p1p2 vector z coordinate
  32280. var p3p2x = 0.0; // p3p2 vector x coordinate
  32281. var p3p2y = 0.0; // p3p2 vector y coordinate
  32282. var p3p2z = 0.0; // p3p2 vector z coordinate
  32283. var faceNormalx = 0.0; // facet normal x coordinate
  32284. var faceNormaly = 0.0; // facet normal y coordinate
  32285. var faceNormalz = 0.0; // facet normal z coordinate
  32286. var length = 0.0; // facet normal length before normalization
  32287. var v1x = 0; // vector1 x index in the positions array
  32288. var v1y = 0; // vector1 y index in the positions array
  32289. var v1z = 0; // vector1 z index in the positions array
  32290. var v2x = 0; // vector2 x index in the positions array
  32291. var v2y = 0; // vector2 y index in the positions array
  32292. var v2z = 0; // vector2 z index in the positions array
  32293. var v3x = 0; // vector3 x index in the positions array
  32294. var v3y = 0; // vector3 y index in the positions array
  32295. var v3z = 0; // vector3 z index in the positions array
  32296. var computeFacetNormals = false;
  32297. var computeFacetPositions = false;
  32298. var computeFacetPartitioning = false;
  32299. var computeDepthSort = false;
  32300. var faceNormalSign = 1;
  32301. var ratio = 0;
  32302. var distanceTo = null;
  32303. if (options) {
  32304. computeFacetNormals = (options.facetNormals) ? true : false;
  32305. computeFacetPositions = (options.facetPositions) ? true : false;
  32306. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32307. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32308. ratio = options.ratio || 0;
  32309. computeDepthSort = (options.depthSort) ? true : false;
  32310. distanceTo = (options.distanceTo);
  32311. if (computeDepthSort) {
  32312. if (distanceTo === undefined) {
  32313. distanceTo = BABYLON.Vector3.Zero();
  32314. }
  32315. var depthSortedFacets = options.depthSortedFacets;
  32316. }
  32317. }
  32318. // facetPartitioning reinit if needed
  32319. var xSubRatio = 0;
  32320. var ySubRatio = 0;
  32321. var zSubRatio = 0;
  32322. var subSq = 0;
  32323. if (computeFacetPartitioning && options && options.bbSize) {
  32324. var ox = 0; // X partitioning index for facet position
  32325. var oy = 0; // Y partinioning index for facet position
  32326. var oz = 0; // Z partinioning index for facet position
  32327. var b1x = 0; // X partitioning index for facet v1 vertex
  32328. var b1y = 0; // Y partitioning index for facet v1 vertex
  32329. var b1z = 0; // z partitioning index for facet v1 vertex
  32330. var b2x = 0; // X partitioning index for facet v2 vertex
  32331. var b2y = 0; // Y partitioning index for facet v2 vertex
  32332. var b2z = 0; // Z partitioning index for facet v2 vertex
  32333. var b3x = 0; // X partitioning index for facet v3 vertex
  32334. var b3y = 0; // Y partitioning index for facet v3 vertex
  32335. var b3z = 0; // Z partitioning index for facet v3 vertex
  32336. var block_idx_o = 0; // facet barycenter block index
  32337. var block_idx_v1 = 0; // v1 vertex block index
  32338. var block_idx_v2 = 0; // v2 vertex block index
  32339. var block_idx_v3 = 0; // v3 vertex block index
  32340. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32341. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32342. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32343. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32344. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32345. subSq = options.subDiv.max * options.subDiv.max;
  32346. options.facetPartitioning.length = 0;
  32347. }
  32348. // reset the normals
  32349. for (index = 0; index < positions.length; index++) {
  32350. normals[index] = 0.0;
  32351. }
  32352. // Loop : 1 indice triplet = 1 facet
  32353. var nbFaces = (indices.length / 3) | 0;
  32354. for (index = 0; index < nbFaces; index++) {
  32355. // get the indexes of the coordinates of each vertex of the facet
  32356. v1x = indices[index * 3] * 3;
  32357. v1y = v1x + 1;
  32358. v1z = v1x + 2;
  32359. v2x = indices[index * 3 + 1] * 3;
  32360. v2y = v2x + 1;
  32361. v2z = v2x + 2;
  32362. v3x = indices[index * 3 + 2] * 3;
  32363. v3y = v3x + 1;
  32364. v3z = v3x + 2;
  32365. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32366. p1p2y = positions[v1y] - positions[v2y];
  32367. p1p2z = positions[v1z] - positions[v2z];
  32368. p3p2x = positions[v3x] - positions[v2x];
  32369. p3p2y = positions[v3y] - positions[v2y];
  32370. p3p2z = positions[v3z] - positions[v2z];
  32371. // compute the face normal with the cross product
  32372. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32373. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32374. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32375. // normalize this normal and store it in the array facetData
  32376. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32377. length = (length === 0) ? 1.0 : length;
  32378. faceNormalx /= length;
  32379. faceNormaly /= length;
  32380. faceNormalz /= length;
  32381. if (computeFacetNormals && options) {
  32382. options.facetNormals[index].x = faceNormalx;
  32383. options.facetNormals[index].y = faceNormaly;
  32384. options.facetNormals[index].z = faceNormalz;
  32385. }
  32386. if (computeFacetPositions && options) {
  32387. // compute and the facet barycenter coordinates in the array facetPositions
  32388. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32389. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32390. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32391. }
  32392. if (computeFacetPartitioning && options) {
  32393. // store the facet indexes in arrays in the main facetPartitioning array :
  32394. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32395. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32396. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32397. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32398. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32399. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32400. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32401. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32402. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32403. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32404. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32405. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32406. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32407. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32408. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32409. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32410. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32411. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32412. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32413. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32414. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32415. // push each facet index in each block containing the vertex
  32416. options.facetPartitioning[block_idx_v1].push(index);
  32417. if (block_idx_v2 != block_idx_v1) {
  32418. options.facetPartitioning[block_idx_v2].push(index);
  32419. }
  32420. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32421. options.facetPartitioning[block_idx_v3].push(index);
  32422. }
  32423. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32424. options.facetPartitioning[block_idx_o].push(index);
  32425. }
  32426. }
  32427. if (computeDepthSort && options && options.facetPositions) {
  32428. var dsf = depthSortedFacets[index];
  32429. dsf.ind = index * 3;
  32430. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32431. }
  32432. // compute the normals anyway
  32433. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32434. normals[v1y] += faceNormaly;
  32435. normals[v1z] += faceNormalz;
  32436. normals[v2x] += faceNormalx;
  32437. normals[v2y] += faceNormaly;
  32438. normals[v2z] += faceNormalz;
  32439. normals[v3x] += faceNormalx;
  32440. normals[v3y] += faceNormaly;
  32441. normals[v3z] += faceNormalz;
  32442. }
  32443. // last normalization of each normal
  32444. for (index = 0; index < normals.length / 3; index++) {
  32445. faceNormalx = normals[index * 3];
  32446. faceNormaly = normals[index * 3 + 1];
  32447. faceNormalz = normals[index * 3 + 2];
  32448. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32449. length = (length === 0) ? 1.0 : length;
  32450. faceNormalx /= length;
  32451. faceNormaly /= length;
  32452. faceNormalz /= length;
  32453. normals[index * 3] = faceNormalx;
  32454. normals[index * 3 + 1] = faceNormaly;
  32455. normals[index * 3 + 2] = faceNormalz;
  32456. }
  32457. };
  32458. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32459. var li = indices.length;
  32460. var ln = normals.length;
  32461. var i;
  32462. var n;
  32463. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32464. switch (sideOrientation) {
  32465. case BABYLON.Mesh.FRONTSIDE:
  32466. // nothing changed
  32467. break;
  32468. case BABYLON.Mesh.BACKSIDE:
  32469. var tmp;
  32470. // indices
  32471. for (i = 0; i < li; i += 3) {
  32472. tmp = indices[i];
  32473. indices[i] = indices[i + 2];
  32474. indices[i + 2] = tmp;
  32475. }
  32476. // normals
  32477. for (n = 0; n < ln; n++) {
  32478. normals[n] = -normals[n];
  32479. }
  32480. break;
  32481. case BABYLON.Mesh.DOUBLESIDE:
  32482. // positions
  32483. var lp = positions.length;
  32484. var l = lp / 3;
  32485. for (var p = 0; p < lp; p++) {
  32486. positions[lp + p] = positions[p];
  32487. }
  32488. // indices
  32489. for (i = 0; i < li; i += 3) {
  32490. indices[i + li] = indices[i + 2] + l;
  32491. indices[i + 1 + li] = indices[i + 1] + l;
  32492. indices[i + 2 + li] = indices[i] + l;
  32493. }
  32494. // normals
  32495. for (n = 0; n < ln; n++) {
  32496. normals[ln + n] = -normals[n];
  32497. }
  32498. // uvs
  32499. var lu = uvs.length;
  32500. var u = 0;
  32501. for (u = 0; u < lu; u++) {
  32502. uvs[u + lu] = uvs[u];
  32503. }
  32504. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32505. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32506. u = 0;
  32507. for (i = 0; i < lu / 2; i++) {
  32508. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32509. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32510. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32511. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32512. u += 2;
  32513. }
  32514. break;
  32515. }
  32516. };
  32517. /**
  32518. * Creates a new VertexData from the imported parameters.
  32519. */
  32520. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32521. var vertexData = new VertexData();
  32522. // positions
  32523. var positions = parsedVertexData.positions;
  32524. if (positions) {
  32525. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32526. }
  32527. // normals
  32528. var normals = parsedVertexData.normals;
  32529. if (normals) {
  32530. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32531. }
  32532. // tangents
  32533. var tangents = parsedVertexData.tangents;
  32534. if (tangents) {
  32535. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32536. }
  32537. // uvs
  32538. var uvs = parsedVertexData.uvs;
  32539. if (uvs) {
  32540. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32541. }
  32542. // uv2s
  32543. var uv2s = parsedVertexData.uv2s;
  32544. if (uv2s) {
  32545. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32546. }
  32547. // uv3s
  32548. var uv3s = parsedVertexData.uv3s;
  32549. if (uv3s) {
  32550. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32551. }
  32552. // uv4s
  32553. var uv4s = parsedVertexData.uv4s;
  32554. if (uv4s) {
  32555. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32556. }
  32557. // uv5s
  32558. var uv5s = parsedVertexData.uv5s;
  32559. if (uv5s) {
  32560. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32561. }
  32562. // uv6s
  32563. var uv6s = parsedVertexData.uv6s;
  32564. if (uv6s) {
  32565. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32566. }
  32567. // colors
  32568. var colors = parsedVertexData.colors;
  32569. if (colors) {
  32570. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32571. }
  32572. // matricesIndices
  32573. var matricesIndices = parsedVertexData.matricesIndices;
  32574. if (matricesIndices) {
  32575. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32576. }
  32577. // matricesWeights
  32578. var matricesWeights = parsedVertexData.matricesWeights;
  32579. if (matricesWeights) {
  32580. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32581. }
  32582. // indices
  32583. var indices = parsedVertexData.indices;
  32584. if (indices) {
  32585. vertexData.indices = indices;
  32586. }
  32587. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32588. };
  32589. return VertexData;
  32590. }());
  32591. BABYLON.VertexData = VertexData;
  32592. })(BABYLON || (BABYLON = {}));
  32593. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32594. var BABYLON;
  32595. (function (BABYLON) {
  32596. /**
  32597. * Class used to store geometry data (vertex buffers + index buffer)
  32598. */
  32599. var Geometry = /** @class */ (function () {
  32600. /**
  32601. * Creates a new geometry
  32602. * @param id defines the unique ID
  32603. * @param scene defines the hosting scene
  32604. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32605. * @param updatable defines if geometry must be updatable (false by default)
  32606. * @param mesh defines the mesh that will be associated with the geometry
  32607. */
  32608. function Geometry(id, scene, vertexData, updatable, mesh) {
  32609. if (updatable === void 0) { updatable = false; }
  32610. if (mesh === void 0) { mesh = null; }
  32611. /**
  32612. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32613. */
  32614. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32615. this._totalVertices = 0;
  32616. this._isDisposed = false;
  32617. this._indexBufferIsUpdatable = false;
  32618. this.id = id;
  32619. this._engine = scene.getEngine();
  32620. this._meshes = [];
  32621. this._scene = scene;
  32622. //Init vertex buffer cache
  32623. this._vertexBuffers = {};
  32624. this._indices = [];
  32625. this._updatable = updatable;
  32626. // vertexData
  32627. if (vertexData) {
  32628. this.setAllVerticesData(vertexData, updatable);
  32629. }
  32630. else {
  32631. this._totalVertices = 0;
  32632. this._indices = [];
  32633. }
  32634. if (this._engine.getCaps().vertexArrayObject) {
  32635. this._vertexArrayObjects = {};
  32636. }
  32637. // applyToMesh
  32638. if (mesh) {
  32639. if (mesh.getClassName() === "LinesMesh") {
  32640. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32641. this.updateExtend();
  32642. }
  32643. this.applyToMesh(mesh);
  32644. mesh.computeWorldMatrix(true);
  32645. }
  32646. }
  32647. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32648. /**
  32649. * 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
  32650. */
  32651. get: function () {
  32652. return this._boundingBias;
  32653. },
  32654. /**
  32655. * 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
  32656. */
  32657. set: function (value) {
  32658. if (this._boundingBias && this._boundingBias.equals(value)) {
  32659. return;
  32660. }
  32661. this._boundingBias = value.clone();
  32662. this.updateBoundingInfo(true, null);
  32663. },
  32664. enumerable: true,
  32665. configurable: true
  32666. });
  32667. /**
  32668. * Static function used to attach a new empty geometry to a mesh
  32669. * @param mesh defines the mesh to attach the geometry to
  32670. * @returns the new {BABYLON.Geometry}
  32671. */
  32672. Geometry.CreateGeometryForMesh = function (mesh) {
  32673. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32674. geometry.applyToMesh(mesh);
  32675. return geometry;
  32676. };
  32677. Object.defineProperty(Geometry.prototype, "extend", {
  32678. /**
  32679. * Gets the current extend of the geometry
  32680. */
  32681. get: function () {
  32682. return this._extend;
  32683. },
  32684. enumerable: true,
  32685. configurable: true
  32686. });
  32687. /**
  32688. * Gets the hosting scene
  32689. * @returns the hosting {BABYLON.Scene}
  32690. */
  32691. Geometry.prototype.getScene = function () {
  32692. return this._scene;
  32693. };
  32694. /**
  32695. * Gets the hosting engine
  32696. * @returns the hosting {BABYLON.Engine}
  32697. */
  32698. Geometry.prototype.getEngine = function () {
  32699. return this._engine;
  32700. };
  32701. /**
  32702. * Defines if the geometry is ready to use
  32703. * @returns true if the geometry is ready to be used
  32704. */
  32705. Geometry.prototype.isReady = function () {
  32706. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32707. };
  32708. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32709. /**
  32710. * Gets a value indicating that the geometry should not be serialized
  32711. */
  32712. get: function () {
  32713. for (var index = 0; index < this._meshes.length; index++) {
  32714. if (!this._meshes[index].doNotSerialize) {
  32715. return false;
  32716. }
  32717. }
  32718. return true;
  32719. },
  32720. enumerable: true,
  32721. configurable: true
  32722. });
  32723. /** @ignore */
  32724. Geometry.prototype._rebuild = function () {
  32725. if (this._vertexArrayObjects) {
  32726. this._vertexArrayObjects = {};
  32727. }
  32728. // Index buffer
  32729. if (this._meshes.length !== 0 && this._indices) {
  32730. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32731. }
  32732. // Vertex buffers
  32733. for (var key in this._vertexBuffers) {
  32734. var vertexBuffer = this._vertexBuffers[key];
  32735. vertexBuffer._rebuild();
  32736. }
  32737. };
  32738. /**
  32739. * Affects all gemetry data in one call
  32740. * @param vertexData defines the geometry data
  32741. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32742. */
  32743. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32744. vertexData.applyToGeometry(this, updatable);
  32745. this.notifyUpdate();
  32746. };
  32747. /**
  32748. * Set specific vertex data
  32749. * @param kind defines the data kind (Position, normal, etc...)
  32750. * @param data defines the vertex data to use
  32751. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32752. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32753. */
  32754. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32755. if (updatable === void 0) { updatable = false; }
  32756. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32757. this.setVerticesBuffer(buffer);
  32758. };
  32759. /**
  32760. * Removes a specific vertex data
  32761. * @param kind defines the data kind (Position, normal, etc...)
  32762. */
  32763. Geometry.prototype.removeVerticesData = function (kind) {
  32764. if (this._vertexBuffers[kind]) {
  32765. this._vertexBuffers[kind].dispose();
  32766. delete this._vertexBuffers[kind];
  32767. }
  32768. };
  32769. /**
  32770. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32771. * @param buffer defines the vertex buffer to use
  32772. */
  32773. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32774. var kind = buffer.getKind();
  32775. if (this._vertexBuffers[kind]) {
  32776. this._vertexBuffers[kind].dispose();
  32777. }
  32778. this._vertexBuffers[kind] = buffer;
  32779. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32780. var data = buffer.getData();
  32781. var stride = buffer.getStrideSize();
  32782. this._totalVertices = data.length / stride;
  32783. this.updateExtend(data, stride);
  32784. this._resetPointsArrayCache();
  32785. var meshes = this._meshes;
  32786. var numOfMeshes = meshes.length;
  32787. for (var index = 0; index < numOfMeshes; index++) {
  32788. var mesh = meshes[index];
  32789. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32790. mesh._createGlobalSubMesh(false);
  32791. mesh.computeWorldMatrix(true);
  32792. }
  32793. }
  32794. this.notifyUpdate(kind);
  32795. if (this._vertexArrayObjects) {
  32796. this._disposeVertexArrayObjects();
  32797. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32798. }
  32799. };
  32800. /**
  32801. * Update a specific vertex buffer
  32802. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32803. * It will do nothing if the buffer is not updatable
  32804. * @param kind defines the data kind (Position, normal, etc...)
  32805. * @param data defines the data to use
  32806. * @param offset defines the offset in the target buffer where to store the data
  32807. */
  32808. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32809. var vertexBuffer = this.getVertexBuffer(kind);
  32810. if (!vertexBuffer) {
  32811. return;
  32812. }
  32813. vertexBuffer.updateDirectly(data, offset);
  32814. this.notifyUpdate(kind);
  32815. };
  32816. /**
  32817. * Update a specific vertex buffer
  32818. * This function will create a new buffer if the current one is not updatable
  32819. * @param kind defines the data kind (Position, normal, etc...)
  32820. * @param data defines the data to use
  32821. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32822. */
  32823. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32824. if (updateExtends === void 0) { updateExtends = false; }
  32825. var vertexBuffer = this.getVertexBuffer(kind);
  32826. if (!vertexBuffer) {
  32827. return;
  32828. }
  32829. vertexBuffer.update(data);
  32830. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32831. var stride = vertexBuffer.getStrideSize();
  32832. this._totalVertices = data.length / stride;
  32833. this.updateBoundingInfo(updateExtends, data);
  32834. }
  32835. this.notifyUpdate(kind);
  32836. };
  32837. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32838. if (updateExtends) {
  32839. this.updateExtend(data);
  32840. }
  32841. var meshes = this._meshes;
  32842. var numOfMeshes = meshes.length;
  32843. this._resetPointsArrayCache();
  32844. for (var index = 0; index < numOfMeshes; index++) {
  32845. var mesh = meshes[index];
  32846. if (updateExtends) {
  32847. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32848. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32849. var subMesh = mesh.subMeshes[subIndex];
  32850. subMesh.refreshBoundingInfo();
  32851. }
  32852. }
  32853. }
  32854. };
  32855. /** @ignore */
  32856. Geometry.prototype._bind = function (effect, indexToBind) {
  32857. if (!effect) {
  32858. return;
  32859. }
  32860. if (indexToBind === undefined) {
  32861. indexToBind = this._indexBuffer;
  32862. }
  32863. var vbs = this.getVertexBuffers();
  32864. if (!vbs) {
  32865. return;
  32866. }
  32867. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32868. this._engine.bindBuffers(vbs, indexToBind, effect);
  32869. return;
  32870. }
  32871. // Using VAO
  32872. if (!this._vertexArrayObjects[effect.key]) {
  32873. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32874. }
  32875. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32876. };
  32877. /**
  32878. * Gets total number of vertices
  32879. * @returns the total number of vertices
  32880. */
  32881. Geometry.prototype.getTotalVertices = function () {
  32882. if (!this.isReady()) {
  32883. return 0;
  32884. }
  32885. return this._totalVertices;
  32886. };
  32887. /**
  32888. * Gets a specific vertex data attached to this geometry
  32889. * @param kind defines the data kind (Position, normal, etc...)
  32890. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32891. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32892. * @returns a float array containing vertex data
  32893. */
  32894. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32895. var vertexBuffer = this.getVertexBuffer(kind);
  32896. if (!vertexBuffer) {
  32897. return null;
  32898. }
  32899. var orig = vertexBuffer.getData();
  32900. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32901. return orig;
  32902. }
  32903. else {
  32904. var len = orig.length;
  32905. var copy = [];
  32906. for (var i = 0; i < len; i++) {
  32907. copy.push(orig[i]);
  32908. }
  32909. return copy;
  32910. }
  32911. };
  32912. /**
  32913. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32914. * @param kind defines the data kind (Position, normal, etc...)
  32915. * @returns true if the vertex buffer with the specified kind is updatable
  32916. */
  32917. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32918. var vb = this._vertexBuffers[kind];
  32919. if (!vb) {
  32920. return false;
  32921. }
  32922. return vb.isUpdatable();
  32923. };
  32924. /**
  32925. * Gets a specific vertex buffer
  32926. * @param kind defines the data kind (Position, normal, etc...)
  32927. * @returns a {BABYLON.VertexBuffer}
  32928. */
  32929. Geometry.prototype.getVertexBuffer = function (kind) {
  32930. if (!this.isReady()) {
  32931. return null;
  32932. }
  32933. return this._vertexBuffers[kind];
  32934. };
  32935. /**
  32936. * Returns all vertex buffers
  32937. * @return an object holding all vertex buffers indexed by kind
  32938. */
  32939. Geometry.prototype.getVertexBuffers = function () {
  32940. if (!this.isReady()) {
  32941. return null;
  32942. }
  32943. return this._vertexBuffers;
  32944. };
  32945. /**
  32946. * Gets a boolean indicating if specific vertex buffer is present
  32947. * @param kind defines the data kind (Position, normal, etc...)
  32948. * @returns true if data is present
  32949. */
  32950. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32951. if (!this._vertexBuffers) {
  32952. if (this._delayInfo) {
  32953. return this._delayInfo.indexOf(kind) !== -1;
  32954. }
  32955. return false;
  32956. }
  32957. return this._vertexBuffers[kind] !== undefined;
  32958. };
  32959. /**
  32960. * Gets a list of all attached data kinds (Position, normal, etc...)
  32961. * @returns a list of string containing all kinds
  32962. */
  32963. Geometry.prototype.getVerticesDataKinds = function () {
  32964. var result = [];
  32965. var kind;
  32966. if (!this._vertexBuffers && this._delayInfo) {
  32967. for (kind in this._delayInfo) {
  32968. result.push(kind);
  32969. }
  32970. }
  32971. else {
  32972. for (kind in this._vertexBuffers) {
  32973. result.push(kind);
  32974. }
  32975. }
  32976. return result;
  32977. };
  32978. /**
  32979. * Update index buffer
  32980. * @param indices defines the indices to store in the index buffer
  32981. * @param offset defines the offset in the target buffer where to store the data
  32982. */
  32983. Geometry.prototype.updateIndices = function (indices, offset) {
  32984. if (!this._indexBuffer) {
  32985. return;
  32986. }
  32987. if (!this._indexBufferIsUpdatable) {
  32988. this.setIndices(indices, null, true);
  32989. }
  32990. else {
  32991. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32992. }
  32993. };
  32994. /**
  32995. * Creates a new index buffer
  32996. * @param indices defines the indices to store in the index buffer
  32997. * @param totalVertices defines the total number of vertices (could be null)
  32998. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32999. */
  33000. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  33001. if (totalVertices === void 0) { totalVertices = null; }
  33002. if (updatable === void 0) { updatable = false; }
  33003. if (this._indexBuffer) {
  33004. this._engine._releaseBuffer(this._indexBuffer);
  33005. }
  33006. this._disposeVertexArrayObjects();
  33007. this._indices = indices;
  33008. this._indexBufferIsUpdatable = updatable;
  33009. if (this._meshes.length !== 0 && this._indices) {
  33010. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  33011. }
  33012. if (totalVertices != undefined) {
  33013. this._totalVertices = totalVertices;
  33014. }
  33015. var meshes = this._meshes;
  33016. var numOfMeshes = meshes.length;
  33017. for (var index = 0; index < numOfMeshes; index++) {
  33018. meshes[index]._createGlobalSubMesh(true);
  33019. }
  33020. this.notifyUpdate();
  33021. };
  33022. /**
  33023. * Return the total number of indices
  33024. * @returns the total number of indices
  33025. */
  33026. Geometry.prototype.getTotalIndices = function () {
  33027. if (!this.isReady()) {
  33028. return 0;
  33029. }
  33030. return this._indices.length;
  33031. };
  33032. /**
  33033. * Gets the index buffer array
  33034. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33035. * @returns the index buffer array
  33036. */
  33037. Geometry.prototype.getIndices = function (copyWhenShared) {
  33038. if (!this.isReady()) {
  33039. return null;
  33040. }
  33041. var orig = this._indices;
  33042. if (!copyWhenShared || this._meshes.length === 1) {
  33043. return orig;
  33044. }
  33045. else {
  33046. var len = orig.length;
  33047. var copy = [];
  33048. for (var i = 0; i < len; i++) {
  33049. copy.push(orig[i]);
  33050. }
  33051. return copy;
  33052. }
  33053. };
  33054. /**
  33055. * Gets the index buffer
  33056. * @return the index buffer
  33057. */
  33058. Geometry.prototype.getIndexBuffer = function () {
  33059. if (!this.isReady()) {
  33060. return null;
  33061. }
  33062. return this._indexBuffer;
  33063. };
  33064. /** @ignore */
  33065. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  33066. if (effect === void 0) { effect = null; }
  33067. if (!effect || !this._vertexArrayObjects) {
  33068. return;
  33069. }
  33070. if (this._vertexArrayObjects[effect.key]) {
  33071. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  33072. delete this._vertexArrayObjects[effect.key];
  33073. }
  33074. };
  33075. /**
  33076. * Release the associated resources for a specific mesh
  33077. * @param mesh defines the source mesh
  33078. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  33079. */
  33080. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33081. var meshes = this._meshes;
  33082. var index = meshes.indexOf(mesh);
  33083. if (index === -1) {
  33084. return;
  33085. }
  33086. meshes.splice(index, 1);
  33087. mesh._geometry = null;
  33088. if (meshes.length === 0 && shouldDispose) {
  33089. this.dispose();
  33090. }
  33091. };
  33092. /**
  33093. * Apply current geometry to a given mesh
  33094. * @param mesh defines the mesh to apply geometry to
  33095. */
  33096. Geometry.prototype.applyToMesh = function (mesh) {
  33097. if (mesh._geometry === this) {
  33098. return;
  33099. }
  33100. var previousGeometry = mesh._geometry;
  33101. if (previousGeometry) {
  33102. previousGeometry.releaseForMesh(mesh);
  33103. }
  33104. var meshes = this._meshes;
  33105. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33106. mesh._geometry = this;
  33107. this._scene.pushGeometry(this);
  33108. meshes.push(mesh);
  33109. if (this.isReady()) {
  33110. this._applyToMesh(mesh);
  33111. }
  33112. else {
  33113. mesh._boundingInfo = this._boundingInfo;
  33114. }
  33115. };
  33116. Geometry.prototype.updateExtend = function (data, stride) {
  33117. if (data === void 0) { data = null; }
  33118. if (!data) {
  33119. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33120. }
  33121. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33122. };
  33123. Geometry.prototype._applyToMesh = function (mesh) {
  33124. var numOfMeshes = this._meshes.length;
  33125. // vertexBuffers
  33126. for (var kind in this._vertexBuffers) {
  33127. if (numOfMeshes === 1) {
  33128. this._vertexBuffers[kind].create();
  33129. }
  33130. var buffer = this._vertexBuffers[kind].getBuffer();
  33131. if (buffer)
  33132. buffer.references = numOfMeshes;
  33133. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33134. if (!this._extend) {
  33135. this.updateExtend(this._vertexBuffers[kind].getData());
  33136. }
  33137. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33138. mesh._createGlobalSubMesh(false);
  33139. //bounding info was just created again, world matrix should be applied again.
  33140. mesh._updateBoundingInfo();
  33141. }
  33142. }
  33143. // indexBuffer
  33144. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33145. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33146. }
  33147. if (this._indexBuffer) {
  33148. this._indexBuffer.references = numOfMeshes;
  33149. }
  33150. };
  33151. Geometry.prototype.notifyUpdate = function (kind) {
  33152. if (this.onGeometryUpdated) {
  33153. this.onGeometryUpdated(this, kind);
  33154. }
  33155. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33156. var mesh = _a[_i];
  33157. mesh._markSubMeshesAsAttributesDirty();
  33158. }
  33159. };
  33160. /**
  33161. * Load the geometry if it was flagged as delay loaded
  33162. * @param scene defines the hosting scene
  33163. * @param onLoaded defines a callback called when the geometry is loaded
  33164. */
  33165. Geometry.prototype.load = function (scene, onLoaded) {
  33166. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33167. return;
  33168. }
  33169. if (this.isReady()) {
  33170. if (onLoaded) {
  33171. onLoaded();
  33172. }
  33173. return;
  33174. }
  33175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33176. this._queueLoad(scene, onLoaded);
  33177. };
  33178. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33179. var _this = this;
  33180. if (!this.delayLoadingFile) {
  33181. return;
  33182. }
  33183. scene._addPendingData(this);
  33184. scene._loadFile(this.delayLoadingFile, function (data) {
  33185. if (!_this._delayLoadingFunction) {
  33186. return;
  33187. }
  33188. _this._delayLoadingFunction(JSON.parse(data), _this);
  33189. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33190. _this._delayInfo = [];
  33191. scene._removePendingData(_this);
  33192. var meshes = _this._meshes;
  33193. var numOfMeshes = meshes.length;
  33194. for (var index = 0; index < numOfMeshes; index++) {
  33195. _this._applyToMesh(meshes[index]);
  33196. }
  33197. if (onLoaded) {
  33198. onLoaded();
  33199. }
  33200. }, undefined, true);
  33201. };
  33202. /**
  33203. * Invert the geometry to move from a right handed system to a left handed one.
  33204. */
  33205. Geometry.prototype.toLeftHanded = function () {
  33206. // Flip faces
  33207. var tIndices = this.getIndices(false);
  33208. if (tIndices != null && tIndices.length > 0) {
  33209. for (var i = 0; i < tIndices.length; i += 3) {
  33210. var tTemp = tIndices[i + 0];
  33211. tIndices[i + 0] = tIndices[i + 2];
  33212. tIndices[i + 2] = tTemp;
  33213. }
  33214. this.setIndices(tIndices);
  33215. }
  33216. // Negate position.z
  33217. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33218. if (tPositions != null && tPositions.length > 0) {
  33219. for (var i = 0; i < tPositions.length; i += 3) {
  33220. tPositions[i + 2] = -tPositions[i + 2];
  33221. }
  33222. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33223. }
  33224. // Negate normal.z
  33225. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33226. if (tNormals != null && tNormals.length > 0) {
  33227. for (var i = 0; i < tNormals.length; i += 3) {
  33228. tNormals[i + 2] = -tNormals[i + 2];
  33229. }
  33230. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33231. }
  33232. };
  33233. // Cache
  33234. /** @ignore */
  33235. Geometry.prototype._resetPointsArrayCache = function () {
  33236. this._positions = null;
  33237. };
  33238. /** @ignore */
  33239. Geometry.prototype._generatePointsArray = function () {
  33240. if (this._positions)
  33241. return true;
  33242. this._positions = [];
  33243. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33244. if (!data) {
  33245. return false;
  33246. }
  33247. for (var index = 0; index < data.length; index += 3) {
  33248. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33249. }
  33250. return true;
  33251. };
  33252. /**
  33253. * Gets a value indicating if the geometry is disposed
  33254. * @returns true if the geometry was disposed
  33255. */
  33256. Geometry.prototype.isDisposed = function () {
  33257. return this._isDisposed;
  33258. };
  33259. Geometry.prototype._disposeVertexArrayObjects = function () {
  33260. if (this._vertexArrayObjects) {
  33261. for (var kind in this._vertexArrayObjects) {
  33262. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33263. }
  33264. this._vertexArrayObjects = {};
  33265. }
  33266. };
  33267. /**
  33268. * Free all associated resources
  33269. */
  33270. Geometry.prototype.dispose = function () {
  33271. var meshes = this._meshes;
  33272. var numOfMeshes = meshes.length;
  33273. var index;
  33274. for (index = 0; index < numOfMeshes; index++) {
  33275. this.releaseForMesh(meshes[index]);
  33276. }
  33277. this._meshes = [];
  33278. this._disposeVertexArrayObjects();
  33279. for (var kind in this._vertexBuffers) {
  33280. this._vertexBuffers[kind].dispose();
  33281. }
  33282. this._vertexBuffers = {};
  33283. this._totalVertices = 0;
  33284. if (this._indexBuffer) {
  33285. this._engine._releaseBuffer(this._indexBuffer);
  33286. }
  33287. this._indexBuffer = null;
  33288. this._indices = [];
  33289. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33290. this.delayLoadingFile = null;
  33291. this._delayLoadingFunction = null;
  33292. this._delayInfo = [];
  33293. this._boundingInfo = null;
  33294. this._scene.removeGeometry(this);
  33295. this._isDisposed = true;
  33296. };
  33297. /**
  33298. * Clone the current geometry into a new geometry
  33299. * @param id defines the unique ID of the new geometry
  33300. * @returns a new geometry object
  33301. */
  33302. Geometry.prototype.copy = function (id) {
  33303. var vertexData = new BABYLON.VertexData();
  33304. vertexData.indices = [];
  33305. var indices = this.getIndices();
  33306. if (indices) {
  33307. for (var index = 0; index < indices.length; index++) {
  33308. vertexData.indices.push(indices[index]);
  33309. }
  33310. }
  33311. var updatable = false;
  33312. var stopChecking = false;
  33313. var kind;
  33314. for (kind in this._vertexBuffers) {
  33315. // using slice() to make a copy of the array and not just reference it
  33316. var data = this.getVerticesData(kind);
  33317. if (data instanceof Float32Array) {
  33318. vertexData.set(new Float32Array(data), kind);
  33319. }
  33320. else {
  33321. vertexData.set(data.slice(0), kind);
  33322. }
  33323. if (!stopChecking) {
  33324. var vb = this.getVertexBuffer(kind);
  33325. if (vb) {
  33326. updatable = vb.isUpdatable();
  33327. stopChecking = !updatable;
  33328. }
  33329. }
  33330. }
  33331. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33332. geometry.delayLoadState = this.delayLoadState;
  33333. geometry.delayLoadingFile = this.delayLoadingFile;
  33334. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33335. for (kind in this._delayInfo) {
  33336. geometry._delayInfo = geometry._delayInfo || [];
  33337. geometry._delayInfo.push(kind);
  33338. }
  33339. // Bounding info
  33340. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33341. return geometry;
  33342. };
  33343. /**
  33344. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33345. * @return a JSON representation of the current geometry data (without the vertices data)
  33346. */
  33347. Geometry.prototype.serialize = function () {
  33348. var serializationObject = {};
  33349. serializationObject.id = this.id;
  33350. serializationObject.updatable = this._updatable;
  33351. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33352. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33353. }
  33354. return serializationObject;
  33355. };
  33356. Geometry.prototype.toNumberArray = function (origin) {
  33357. if (Array.isArray(origin)) {
  33358. return origin;
  33359. }
  33360. else {
  33361. return Array.prototype.slice.call(origin);
  33362. }
  33363. };
  33364. /**
  33365. * Serialize all vertices data into a JSON oject
  33366. * @returns a JSON representation of the current geometry data
  33367. */
  33368. Geometry.prototype.serializeVerticeData = function () {
  33369. var serializationObject = this.serialize();
  33370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33371. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33372. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33373. serializationObject.positions._updatable = true;
  33374. }
  33375. }
  33376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33377. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33378. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33379. serializationObject.normals._updatable = true;
  33380. }
  33381. }
  33382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33383. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33384. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33385. serializationObject.tangets._updatable = true;
  33386. }
  33387. }
  33388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33389. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33391. serializationObject.uvs._updatable = true;
  33392. }
  33393. }
  33394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33395. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33397. serializationObject.uv2s._updatable = true;
  33398. }
  33399. }
  33400. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33401. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33402. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33403. serializationObject.uv3s._updatable = true;
  33404. }
  33405. }
  33406. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33407. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33408. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33409. serializationObject.uv4s._updatable = true;
  33410. }
  33411. }
  33412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33413. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33414. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33415. serializationObject.uv5s._updatable = true;
  33416. }
  33417. }
  33418. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33419. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33420. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33421. serializationObject.uv6s._updatable = true;
  33422. }
  33423. }
  33424. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33425. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33426. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33427. serializationObject.colors._updatable = true;
  33428. }
  33429. }
  33430. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33431. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33432. serializationObject.matricesIndices._isExpanded = true;
  33433. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33434. serializationObject.matricesIndices._updatable = true;
  33435. }
  33436. }
  33437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33438. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33439. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33440. serializationObject.matricesWeights._updatable = true;
  33441. }
  33442. }
  33443. serializationObject.indices = this.toNumberArray(this.getIndices());
  33444. return serializationObject;
  33445. };
  33446. // Statics
  33447. /**
  33448. * Extracts a clone of a mesh geometry
  33449. * @param mesh defines the source mesh
  33450. * @param id defines the unique ID of the new geometry object
  33451. * @returns the new geometry object
  33452. */
  33453. Geometry.ExtractFromMesh = function (mesh, id) {
  33454. var geometry = mesh._geometry;
  33455. if (!geometry) {
  33456. return null;
  33457. }
  33458. return geometry.copy(id);
  33459. };
  33460. /**
  33461. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33462. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33463. * Be aware Math.random() could cause collisions, but:
  33464. * "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"
  33465. * @returns a string containing a new GUID
  33466. */
  33467. Geometry.RandomId = function () {
  33468. return BABYLON.Tools.RandomId();
  33469. };
  33470. /** @ignore */
  33471. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33472. var scene = mesh.getScene();
  33473. // Geometry
  33474. var geometryId = parsedGeometry.geometryId;
  33475. if (geometryId) {
  33476. var geometry = scene.getGeometryByID(geometryId);
  33477. if (geometry) {
  33478. geometry.applyToMesh(mesh);
  33479. }
  33480. }
  33481. else if (parsedGeometry instanceof ArrayBuffer) {
  33482. var binaryInfo = mesh._binaryInfo;
  33483. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33484. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33485. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33486. }
  33487. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33488. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33489. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33490. }
  33491. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33492. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33493. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33494. }
  33495. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33496. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33497. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33498. }
  33499. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33500. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33501. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33502. }
  33503. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33504. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33505. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33506. }
  33507. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33508. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33509. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33510. }
  33511. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33512. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33513. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33514. }
  33515. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33516. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33517. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33518. }
  33519. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33520. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33521. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33522. }
  33523. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33524. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33525. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33526. }
  33527. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33528. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33529. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33530. }
  33531. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33532. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33533. mesh.setIndices(indicesData, null);
  33534. }
  33535. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33536. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33537. mesh.subMeshes = [];
  33538. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33539. var materialIndex = subMeshesData[(i * 5) + 0];
  33540. var verticesStart = subMeshesData[(i * 5) + 1];
  33541. var verticesCount = subMeshesData[(i * 5) + 2];
  33542. var indexStart = subMeshesData[(i * 5) + 3];
  33543. var indexCount = subMeshesData[(i * 5) + 4];
  33544. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33545. }
  33546. }
  33547. }
  33548. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33549. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33550. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33551. if (parsedGeometry.tangents) {
  33552. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33553. }
  33554. if (parsedGeometry.uvs) {
  33555. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33556. }
  33557. if (parsedGeometry.uvs2) {
  33558. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33559. }
  33560. if (parsedGeometry.uvs3) {
  33561. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33562. }
  33563. if (parsedGeometry.uvs4) {
  33564. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33565. }
  33566. if (parsedGeometry.uvs5) {
  33567. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33568. }
  33569. if (parsedGeometry.uvs6) {
  33570. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33571. }
  33572. if (parsedGeometry.colors) {
  33573. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33574. }
  33575. if (parsedGeometry.matricesIndices) {
  33576. if (!parsedGeometry.matricesIndices._isExpanded) {
  33577. var floatIndices = [];
  33578. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33579. var matricesIndex = parsedGeometry.matricesIndices[i];
  33580. floatIndices.push(matricesIndex & 0x000000FF);
  33581. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33582. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33583. floatIndices.push(matricesIndex >> 24);
  33584. }
  33585. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33586. }
  33587. else {
  33588. delete parsedGeometry.matricesIndices._isExpanded;
  33589. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33590. }
  33591. }
  33592. if (parsedGeometry.matricesIndicesExtra) {
  33593. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33594. var floatIndices = [];
  33595. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33596. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33597. floatIndices.push(matricesIndex & 0x000000FF);
  33598. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33599. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33600. floatIndices.push(matricesIndex >> 24);
  33601. }
  33602. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33603. }
  33604. else {
  33605. delete parsedGeometry.matricesIndices._isExpanded;
  33606. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33607. }
  33608. }
  33609. if (parsedGeometry.matricesWeights) {
  33610. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33612. }
  33613. if (parsedGeometry.matricesWeightsExtra) {
  33614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33615. }
  33616. mesh.setIndices(parsedGeometry.indices, null);
  33617. }
  33618. // SubMeshes
  33619. if (parsedGeometry.subMeshes) {
  33620. mesh.subMeshes = [];
  33621. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33622. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33623. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33624. }
  33625. }
  33626. // Flat shading
  33627. if (mesh._shouldGenerateFlatShading) {
  33628. mesh.convertToFlatShadedMesh();
  33629. delete mesh._shouldGenerateFlatShading;
  33630. }
  33631. // Update
  33632. mesh.computeWorldMatrix(true);
  33633. // Octree
  33634. var sceneOctree = scene.selectionOctree;
  33635. if (sceneOctree !== undefined && sceneOctree !== null) {
  33636. sceneOctree.addMesh(mesh);
  33637. }
  33638. };
  33639. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33640. var epsilon = 1e-3;
  33641. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33642. return;
  33643. }
  33644. var noInfluenceBoneIndex = 0.0;
  33645. if (parsedGeometry.skeletonId > -1) {
  33646. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33647. if (!skeleton) {
  33648. return;
  33649. }
  33650. noInfluenceBoneIndex = skeleton.bones.length;
  33651. }
  33652. else {
  33653. return;
  33654. }
  33655. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33656. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33657. var matricesWeights = parsedGeometry.matricesWeights;
  33658. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33659. var influencers = parsedGeometry.numBoneInfluencer;
  33660. var size = matricesWeights.length;
  33661. for (var i = 0; i < size; i += 4) {
  33662. var weight = 0.0;
  33663. var firstZeroWeight = -1;
  33664. for (var j = 0; j < 4; j++) {
  33665. var w = matricesWeights[i + j];
  33666. weight += w;
  33667. if (w < epsilon && firstZeroWeight < 0) {
  33668. firstZeroWeight = j;
  33669. }
  33670. }
  33671. if (matricesWeightsExtra) {
  33672. for (var j = 0; j < 4; j++) {
  33673. var w = matricesWeightsExtra[i + j];
  33674. weight += w;
  33675. if (w < epsilon && firstZeroWeight < 0) {
  33676. firstZeroWeight = j + 4;
  33677. }
  33678. }
  33679. }
  33680. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33681. firstZeroWeight = influencers - 1;
  33682. }
  33683. if (weight > epsilon) {
  33684. var mweight = 1.0 / weight;
  33685. for (var j = 0; j < 4; j++) {
  33686. matricesWeights[i + j] *= mweight;
  33687. }
  33688. if (matricesWeightsExtra) {
  33689. for (var j = 0; j < 4; j++) {
  33690. matricesWeightsExtra[i + j] *= mweight;
  33691. }
  33692. }
  33693. }
  33694. else {
  33695. if (firstZeroWeight >= 4) {
  33696. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33697. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33698. }
  33699. else {
  33700. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33701. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33702. }
  33703. }
  33704. }
  33705. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33706. if (parsedGeometry.matricesWeightsExtra) {
  33707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33708. }
  33709. };
  33710. /**
  33711. * Create a new geometry from persisted data (Using .babylon file format)
  33712. * @param parsedVertexData defines the persisted data
  33713. * @param scene defines the hosting scene
  33714. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33715. * @returns the new geometry object
  33716. */
  33717. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33718. if (scene.getGeometryByID(parsedVertexData.id)) {
  33719. return null; // null since geometry could be something else than a box...
  33720. }
  33721. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33722. if (BABYLON.Tags) {
  33723. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33724. }
  33725. if (parsedVertexData.delayLoadingFile) {
  33726. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33727. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33728. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33729. geometry._delayInfo = [];
  33730. if (parsedVertexData.hasUVs) {
  33731. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33732. }
  33733. if (parsedVertexData.hasUVs2) {
  33734. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33735. }
  33736. if (parsedVertexData.hasUVs3) {
  33737. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33738. }
  33739. if (parsedVertexData.hasUVs4) {
  33740. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33741. }
  33742. if (parsedVertexData.hasUVs5) {
  33743. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33744. }
  33745. if (parsedVertexData.hasUVs6) {
  33746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33747. }
  33748. if (parsedVertexData.hasColors) {
  33749. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33750. }
  33751. if (parsedVertexData.hasMatricesIndices) {
  33752. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33753. }
  33754. if (parsedVertexData.hasMatricesWeights) {
  33755. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33756. }
  33757. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33758. }
  33759. else {
  33760. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33761. }
  33762. scene.pushGeometry(geometry, true);
  33763. return geometry;
  33764. };
  33765. return Geometry;
  33766. }());
  33767. BABYLON.Geometry = Geometry;
  33768. // Primitives
  33769. /// Abstract class
  33770. /**
  33771. * Abstract class used to provide common services for all typed geometries
  33772. */
  33773. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33774. __extends(_PrimitiveGeometry, _super);
  33775. /**
  33776. * Creates a new typed geometry
  33777. * @param id defines the unique ID of the geometry
  33778. * @param scene defines the hosting scene
  33779. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33780. * @param mesh defines the hosting mesh (can be null)
  33781. */
  33782. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33783. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33784. if (mesh === void 0) { mesh = null; }
  33785. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33786. _this._canBeRegenerated = _canBeRegenerated;
  33787. _this._beingRegenerated = true;
  33788. _this.regenerate();
  33789. _this._beingRegenerated = false;
  33790. return _this;
  33791. }
  33792. /**
  33793. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33794. * @returns true if the geometry can be regenerated
  33795. */
  33796. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33797. return this._canBeRegenerated;
  33798. };
  33799. /**
  33800. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33801. */
  33802. _PrimitiveGeometry.prototype.regenerate = function () {
  33803. if (!this._canBeRegenerated) {
  33804. return;
  33805. }
  33806. this._beingRegenerated = true;
  33807. this.setAllVerticesData(this._regenerateVertexData(), false);
  33808. this._beingRegenerated = false;
  33809. };
  33810. /**
  33811. * Clone the geometry
  33812. * @param id defines the unique ID of the new geometry
  33813. * @returns the new geometry
  33814. */
  33815. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33816. return _super.prototype.copy.call(this, id);
  33817. };
  33818. // overrides
  33819. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33820. if (!this._beingRegenerated) {
  33821. return;
  33822. }
  33823. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33824. };
  33825. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33826. if (!this._beingRegenerated) {
  33827. return;
  33828. }
  33829. _super.prototype.setVerticesData.call(this, kind, data, false);
  33830. };
  33831. // to override
  33832. /** @ignore */
  33833. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33834. throw new Error("Abstract method");
  33835. };
  33836. _PrimitiveGeometry.prototype.copy = function (id) {
  33837. throw new Error("Must be overriden in sub-classes.");
  33838. };
  33839. _PrimitiveGeometry.prototype.serialize = function () {
  33840. var serializationObject = _super.prototype.serialize.call(this);
  33841. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33842. return serializationObject;
  33843. };
  33844. return _PrimitiveGeometry;
  33845. }(Geometry));
  33846. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33847. /**
  33848. * Creates a ribbon geometry
  33849. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33850. */
  33851. var RibbonGeometry = /** @class */ (function (_super) {
  33852. __extends(RibbonGeometry, _super);
  33853. /**
  33854. * Creates a ribbon geometry
  33855. * @param id defines the unique ID of the geometry
  33856. * @param scene defines the hosting scene
  33857. * @param pathArray defines the array of paths to use
  33858. * @param closeArray defines if the last path and the first path must be joined
  33859. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33860. * @param offset defines the offset between points
  33861. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33862. * @param mesh defines the hosting mesh (can be null)
  33863. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33864. */
  33865. function RibbonGeometry(id, scene,
  33866. /**
  33867. * Defines the array of paths to use
  33868. */
  33869. pathArray,
  33870. /**
  33871. * Defines if the last and first points of each path in your pathArray must be joined
  33872. */
  33873. closeArray,
  33874. /**
  33875. * Defines if the last and first points of each path in your pathArray must be joined
  33876. */
  33877. closePath,
  33878. /**
  33879. * Defines the offset between points
  33880. */
  33881. offset, canBeRegenerated, mesh,
  33882. /**
  33883. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33884. */
  33885. side) {
  33886. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33887. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33888. _this.pathArray = pathArray;
  33889. _this.closeArray = closeArray;
  33890. _this.closePath = closePath;
  33891. _this.offset = offset;
  33892. _this.side = side;
  33893. return _this;
  33894. }
  33895. /** @ignore */
  33896. RibbonGeometry.prototype._regenerateVertexData = function () {
  33897. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33898. };
  33899. RibbonGeometry.prototype.copy = function (id) {
  33900. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33901. };
  33902. return RibbonGeometry;
  33903. }(_PrimitiveGeometry));
  33904. BABYLON.RibbonGeometry = RibbonGeometry;
  33905. /**
  33906. * Creates a box geometry
  33907. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33908. */
  33909. var BoxGeometry = /** @class */ (function (_super) {
  33910. __extends(BoxGeometry, _super);
  33911. /**
  33912. * Creates a box geometry
  33913. * @param id defines the unique ID of the geometry
  33914. * @param scene defines the hosting scene
  33915. * @param size defines the zise of the box (width, height and depth are the same)
  33916. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33917. * @param mesh defines the hosting mesh (can be null)
  33918. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33919. */
  33920. function BoxGeometry(id, scene,
  33921. /**
  33922. * Defines the zise of the box (width, height and depth are the same)
  33923. */
  33924. size, canBeRegenerated, mesh,
  33925. /**
  33926. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33927. */
  33928. side) {
  33929. if (mesh === void 0) { mesh = null; }
  33930. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33931. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33932. _this.size = size;
  33933. _this.side = side;
  33934. return _this;
  33935. }
  33936. BoxGeometry.prototype._regenerateVertexData = function () {
  33937. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33938. };
  33939. BoxGeometry.prototype.copy = function (id) {
  33940. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33941. };
  33942. BoxGeometry.prototype.serialize = function () {
  33943. var serializationObject = _super.prototype.serialize.call(this);
  33944. serializationObject.size = this.size;
  33945. return serializationObject;
  33946. };
  33947. BoxGeometry.Parse = function (parsedBox, scene) {
  33948. if (scene.getGeometryByID(parsedBox.id)) {
  33949. return null; // null since geometry could be something else than a box...
  33950. }
  33951. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33952. if (BABYLON.Tags) {
  33953. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33954. }
  33955. scene.pushGeometry(box, true);
  33956. return box;
  33957. };
  33958. return BoxGeometry;
  33959. }(_PrimitiveGeometry));
  33960. BABYLON.BoxGeometry = BoxGeometry;
  33961. /**
  33962. * Creates a sphere geometry
  33963. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33964. */
  33965. var SphereGeometry = /** @class */ (function (_super) {
  33966. __extends(SphereGeometry, _super);
  33967. /**
  33968. * Create a new sphere geometry
  33969. * @param id defines the unique ID of the geometry
  33970. * @param scene defines the hosting scene
  33971. * @param segments defines the number of segments to use to create the sphere
  33972. * @param diameter defines the diameter of the sphere
  33973. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33974. * @param mesh defines the hosting mesh (can be null)
  33975. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33976. */
  33977. function SphereGeometry(id, scene,
  33978. /**
  33979. * Defines the number of segments to use to create the sphere
  33980. */
  33981. segments,
  33982. /**
  33983. * Defines the diameter of the sphere
  33984. */
  33985. diameter, canBeRegenerated, mesh,
  33986. /**
  33987. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33988. */
  33989. side) {
  33990. if (mesh === void 0) { mesh = null; }
  33991. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33992. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33993. _this.segments = segments;
  33994. _this.diameter = diameter;
  33995. _this.side = side;
  33996. return _this;
  33997. }
  33998. SphereGeometry.prototype._regenerateVertexData = function () {
  33999. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34000. };
  34001. SphereGeometry.prototype.copy = function (id) {
  34002. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34003. };
  34004. SphereGeometry.prototype.serialize = function () {
  34005. var serializationObject = _super.prototype.serialize.call(this);
  34006. serializationObject.segments = this.segments;
  34007. serializationObject.diameter = this.diameter;
  34008. return serializationObject;
  34009. };
  34010. SphereGeometry.Parse = function (parsedSphere, scene) {
  34011. if (scene.getGeometryByID(parsedSphere.id)) {
  34012. return null; // null since geometry could be something else than a sphere...
  34013. }
  34014. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34015. if (BABYLON.Tags) {
  34016. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34017. }
  34018. scene.pushGeometry(sphere, true);
  34019. return sphere;
  34020. };
  34021. return SphereGeometry;
  34022. }(_PrimitiveGeometry));
  34023. BABYLON.SphereGeometry = SphereGeometry;
  34024. /**
  34025. * Creates a disc geometry
  34026. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  34027. */
  34028. var DiscGeometry = /** @class */ (function (_super) {
  34029. __extends(DiscGeometry, _super);
  34030. /**
  34031. * Creates a new disc geometry
  34032. * @param id defines the unique ID of the geometry
  34033. * @param scene defines the hosting scene
  34034. * @param radius defines the radius of the disc
  34035. * @param tessellation defines the tesselation factor to apply to the disc
  34036. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34037. * @param mesh defines the hosting mesh (can be null)
  34038. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34039. */
  34040. function DiscGeometry(id, scene,
  34041. /**
  34042. * Defines the radius of the disc
  34043. */
  34044. radius,
  34045. /**
  34046. * Defines the tesselation factor to apply to the disc
  34047. */
  34048. tessellation, canBeRegenerated, mesh,
  34049. /**
  34050. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34051. */
  34052. side) {
  34053. if (mesh === void 0) { mesh = null; }
  34054. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34055. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34056. _this.radius = radius;
  34057. _this.tessellation = tessellation;
  34058. _this.side = side;
  34059. return _this;
  34060. }
  34061. DiscGeometry.prototype._regenerateVertexData = function () {
  34062. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34063. };
  34064. DiscGeometry.prototype.copy = function (id) {
  34065. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34066. };
  34067. return DiscGeometry;
  34068. }(_PrimitiveGeometry));
  34069. BABYLON.DiscGeometry = DiscGeometry;
  34070. /**
  34071. * Creates a new cylinder geometry
  34072. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  34073. */
  34074. var CylinderGeometry = /** @class */ (function (_super) {
  34075. __extends(CylinderGeometry, _super);
  34076. /**
  34077. * Creates a new cylinder geometry
  34078. * @param id defines the unique ID of the geometry
  34079. * @param scene defines the hosting scene
  34080. * @param height defines the height of the cylinder
  34081. * @param diameterTop defines the diameter of the cylinder's top cap
  34082. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  34083. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  34084. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  34085. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34086. * @param mesh defines the hosting mesh (can be null)
  34087. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34088. */
  34089. function CylinderGeometry(id, scene,
  34090. /**
  34091. * Defines the height of the cylinder
  34092. */
  34093. height,
  34094. /**
  34095. * Defines the diameter of the cylinder's top cap
  34096. */
  34097. diameterTop,
  34098. /**
  34099. * Defines the diameter of the cylinder's bottom cap
  34100. */
  34101. diameterBottom,
  34102. /**
  34103. * Defines the tessellation factor to apply to the cylinder
  34104. */
  34105. tessellation,
  34106. /**
  34107. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  34108. */
  34109. subdivisions, canBeRegenerated, mesh,
  34110. /**
  34111. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34112. */
  34113. side) {
  34114. if (subdivisions === void 0) { subdivisions = 1; }
  34115. if (mesh === void 0) { mesh = null; }
  34116. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34117. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34118. _this.height = height;
  34119. _this.diameterTop = diameterTop;
  34120. _this.diameterBottom = diameterBottom;
  34121. _this.tessellation = tessellation;
  34122. _this.subdivisions = subdivisions;
  34123. _this.side = side;
  34124. return _this;
  34125. }
  34126. CylinderGeometry.prototype._regenerateVertexData = function () {
  34127. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34128. };
  34129. CylinderGeometry.prototype.copy = function (id) {
  34130. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34131. };
  34132. CylinderGeometry.prototype.serialize = function () {
  34133. var serializationObject = _super.prototype.serialize.call(this);
  34134. serializationObject.height = this.height;
  34135. serializationObject.diameterTop = this.diameterTop;
  34136. serializationObject.diameterBottom = this.diameterBottom;
  34137. serializationObject.tessellation = this.tessellation;
  34138. return serializationObject;
  34139. };
  34140. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34141. if (scene.getGeometryByID(parsedCylinder.id)) {
  34142. return null; // null since geometry could be something else than a cylinder...
  34143. }
  34144. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34145. if (BABYLON.Tags) {
  34146. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34147. }
  34148. scene.pushGeometry(cylinder, true);
  34149. return cylinder;
  34150. };
  34151. return CylinderGeometry;
  34152. }(_PrimitiveGeometry));
  34153. BABYLON.CylinderGeometry = CylinderGeometry;
  34154. /**
  34155. * Creates a new torus geometry
  34156. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34157. */
  34158. var TorusGeometry = /** @class */ (function (_super) {
  34159. __extends(TorusGeometry, _super);
  34160. /**
  34161. * Creates a new torus geometry
  34162. * @param id defines the unique ID of the geometry
  34163. * @param scene defines the hosting scene
  34164. * @param diameter defines the diameter of the torus
  34165. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34166. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34167. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34168. * @param mesh defines the hosting mesh (can be null)
  34169. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34170. */
  34171. function TorusGeometry(id, scene,
  34172. /**
  34173. * Defines the diameter of the torus
  34174. */
  34175. diameter,
  34176. /**
  34177. * Defines the thickness of the torus (ie. internal diameter)
  34178. */
  34179. thickness,
  34180. /**
  34181. * Defines the tesselation factor to apply to the torus
  34182. */
  34183. tessellation, canBeRegenerated, mesh,
  34184. /**
  34185. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34186. */
  34187. side) {
  34188. if (mesh === void 0) { mesh = null; }
  34189. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34190. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34191. _this.diameter = diameter;
  34192. _this.thickness = thickness;
  34193. _this.tessellation = tessellation;
  34194. _this.side = side;
  34195. return _this;
  34196. }
  34197. TorusGeometry.prototype._regenerateVertexData = function () {
  34198. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34199. };
  34200. TorusGeometry.prototype.copy = function (id) {
  34201. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34202. };
  34203. TorusGeometry.prototype.serialize = function () {
  34204. var serializationObject = _super.prototype.serialize.call(this);
  34205. serializationObject.diameter = this.diameter;
  34206. serializationObject.thickness = this.thickness;
  34207. serializationObject.tessellation = this.tessellation;
  34208. return serializationObject;
  34209. };
  34210. TorusGeometry.Parse = function (parsedTorus, scene) {
  34211. if (scene.getGeometryByID(parsedTorus.id)) {
  34212. return null; // null since geometry could be something else than a torus...
  34213. }
  34214. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34215. if (BABYLON.Tags) {
  34216. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34217. }
  34218. scene.pushGeometry(torus, true);
  34219. return torus;
  34220. };
  34221. return TorusGeometry;
  34222. }(_PrimitiveGeometry));
  34223. BABYLON.TorusGeometry = TorusGeometry;
  34224. /**
  34225. * Creates a new ground geometry
  34226. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34227. */
  34228. var GroundGeometry = /** @class */ (function (_super) {
  34229. __extends(GroundGeometry, _super);
  34230. /**
  34231. * Creates a new ground geometry
  34232. * @param id defines the unique ID of the geometry
  34233. * @param scene defines the hosting scene
  34234. * @param width defines the width of the ground
  34235. * @param height defines the height of the ground
  34236. * @param subdivisions defines the subdivisions to apply to the ground
  34237. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34238. * @param mesh defines the hosting mesh (can be null)
  34239. */
  34240. function GroundGeometry(id, scene,
  34241. /**
  34242. * Defines the width of the ground
  34243. */
  34244. width,
  34245. /**
  34246. * Defines the height of the ground
  34247. */
  34248. height,
  34249. /**
  34250. * Defines the subdivisions to apply to the ground
  34251. */
  34252. subdivisions, canBeRegenerated, mesh) {
  34253. if (mesh === void 0) { mesh = null; }
  34254. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34255. _this.width = width;
  34256. _this.height = height;
  34257. _this.subdivisions = subdivisions;
  34258. return _this;
  34259. }
  34260. GroundGeometry.prototype._regenerateVertexData = function () {
  34261. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34262. };
  34263. GroundGeometry.prototype.copy = function (id) {
  34264. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34265. };
  34266. GroundGeometry.prototype.serialize = function () {
  34267. var serializationObject = _super.prototype.serialize.call(this);
  34268. serializationObject.width = this.width;
  34269. serializationObject.height = this.height;
  34270. serializationObject.subdivisions = this.subdivisions;
  34271. return serializationObject;
  34272. };
  34273. GroundGeometry.Parse = function (parsedGround, scene) {
  34274. if (scene.getGeometryByID(parsedGround.id)) {
  34275. return null; // null since geometry could be something else than a ground...
  34276. }
  34277. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34278. if (BABYLON.Tags) {
  34279. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34280. }
  34281. scene.pushGeometry(ground, true);
  34282. return ground;
  34283. };
  34284. return GroundGeometry;
  34285. }(_PrimitiveGeometry));
  34286. BABYLON.GroundGeometry = GroundGeometry;
  34287. /**
  34288. * Creates a tiled ground geometry
  34289. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34290. */
  34291. var TiledGroundGeometry = /** @class */ (function (_super) {
  34292. __extends(TiledGroundGeometry, _super);
  34293. /**
  34294. * Creates a tiled ground geometry
  34295. * @param id defines the unique ID of the geometry
  34296. * @param scene defines the hosting scene
  34297. * @param xmin defines the minimum value on X axis
  34298. * @param zmin defines the minimum value on Z axis
  34299. * @param xmax defines the maximum value on X axis
  34300. * @param zmax defines the maximum value on Z axis
  34301. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34302. * @param precision defines the precision to use when computing the tiles
  34303. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34304. * @param mesh defines the hosting mesh (can be null)
  34305. */
  34306. function TiledGroundGeometry(id, scene,
  34307. /**
  34308. * Defines the minimum value on X axis
  34309. */
  34310. xmin,
  34311. /**
  34312. * Defines the minimum value on Z axis
  34313. */
  34314. zmin,
  34315. /**
  34316. * Defines the maximum value on X axis
  34317. */
  34318. xmax,
  34319. /**
  34320. * Defines the maximum value on Z axis
  34321. */
  34322. zmax,
  34323. /**
  34324. * Defines the subdivisions to apply to the ground
  34325. */
  34326. subdivisions,
  34327. /**
  34328. * Defines the precision to use when computing the tiles
  34329. */
  34330. precision, canBeRegenerated, mesh) {
  34331. if (mesh === void 0) { mesh = null; }
  34332. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34333. _this.xmin = xmin;
  34334. _this.zmin = zmin;
  34335. _this.xmax = xmax;
  34336. _this.zmax = zmax;
  34337. _this.subdivisions = subdivisions;
  34338. _this.precision = precision;
  34339. return _this;
  34340. }
  34341. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34342. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34343. };
  34344. TiledGroundGeometry.prototype.copy = function (id) {
  34345. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34346. };
  34347. return TiledGroundGeometry;
  34348. }(_PrimitiveGeometry));
  34349. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34350. /**
  34351. * Creates a plane geometry
  34352. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34353. */
  34354. var PlaneGeometry = /** @class */ (function (_super) {
  34355. __extends(PlaneGeometry, _super);
  34356. /**
  34357. * Creates a plane geometry
  34358. * @param id defines the unique ID of the geometry
  34359. * @param scene defines the hosting scene
  34360. * @param size defines the size of the plane (width === height)
  34361. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34362. * @param mesh defines the hosting mesh (can be null)
  34363. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34364. */
  34365. function PlaneGeometry(id, scene,
  34366. /**
  34367. * Defines the size of the plane (width === height)
  34368. */
  34369. size, canBeRegenerated, mesh,
  34370. /**
  34371. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34372. */
  34373. side) {
  34374. if (mesh === void 0) { mesh = null; }
  34375. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34376. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34377. _this.size = size;
  34378. _this.side = side;
  34379. return _this;
  34380. }
  34381. PlaneGeometry.prototype._regenerateVertexData = function () {
  34382. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34383. };
  34384. PlaneGeometry.prototype.copy = function (id) {
  34385. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34386. };
  34387. PlaneGeometry.prototype.serialize = function () {
  34388. var serializationObject = _super.prototype.serialize.call(this);
  34389. serializationObject.size = this.size;
  34390. return serializationObject;
  34391. };
  34392. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34393. if (scene.getGeometryByID(parsedPlane.id)) {
  34394. return null; // null since geometry could be something else than a ground...
  34395. }
  34396. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34397. if (BABYLON.Tags) {
  34398. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34399. }
  34400. scene.pushGeometry(plane, true);
  34401. return plane;
  34402. };
  34403. return PlaneGeometry;
  34404. }(_PrimitiveGeometry));
  34405. BABYLON.PlaneGeometry = PlaneGeometry;
  34406. /**
  34407. * Creates a torus knot geometry
  34408. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34409. */
  34410. var TorusKnotGeometry = /** @class */ (function (_super) {
  34411. __extends(TorusKnotGeometry, _super);
  34412. /**
  34413. * Creates a torus knot geometry
  34414. * @param id defines the unique ID of the geometry
  34415. * @param scene defines the hosting scene
  34416. * @param radius defines the radius of the torus knot
  34417. * @param tube defines the thickness of the torus knot tube
  34418. * @param radialSegments defines the number of radial segments
  34419. * @param tubularSegments defines the number of tubular segments
  34420. * @param p defines the first number of windings
  34421. * @param q defines the second number of windings
  34422. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34423. * @param mesh defines the hosting mesh (can be null)
  34424. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34425. */
  34426. function TorusKnotGeometry(id, scene,
  34427. /**
  34428. * Defines the radius of the torus knot
  34429. */
  34430. radius,
  34431. /**
  34432. * Defines the thickness of the torus knot tube
  34433. */
  34434. tube,
  34435. /**
  34436. * Defines the number of radial segments
  34437. */
  34438. radialSegments,
  34439. /**
  34440. * Defines the number of tubular segments
  34441. */
  34442. tubularSegments,
  34443. /**
  34444. * Defines the first number of windings
  34445. */
  34446. p,
  34447. /**
  34448. * Defines the second number of windings
  34449. */
  34450. q, canBeRegenerated, mesh,
  34451. /**
  34452. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34453. */
  34454. side) {
  34455. if (mesh === void 0) { mesh = null; }
  34456. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34457. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34458. _this.radius = radius;
  34459. _this.tube = tube;
  34460. _this.radialSegments = radialSegments;
  34461. _this.tubularSegments = tubularSegments;
  34462. _this.p = p;
  34463. _this.q = q;
  34464. _this.side = side;
  34465. return _this;
  34466. }
  34467. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34468. 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 });
  34469. };
  34470. TorusKnotGeometry.prototype.copy = function (id) {
  34471. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34472. };
  34473. TorusKnotGeometry.prototype.serialize = function () {
  34474. var serializationObject = _super.prototype.serialize.call(this);
  34475. serializationObject.radius = this.radius;
  34476. serializationObject.tube = this.tube;
  34477. serializationObject.radialSegments = this.radialSegments;
  34478. serializationObject.tubularSegments = this.tubularSegments;
  34479. serializationObject.p = this.p;
  34480. serializationObject.q = this.q;
  34481. return serializationObject;
  34482. };
  34483. ;
  34484. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34485. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34486. return null; // null since geometry could be something else than a ground...
  34487. }
  34488. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34489. if (BABYLON.Tags) {
  34490. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34491. }
  34492. scene.pushGeometry(torusKnot, true);
  34493. return torusKnot;
  34494. };
  34495. return TorusKnotGeometry;
  34496. }(_PrimitiveGeometry));
  34497. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34498. //}
  34499. })(BABYLON || (BABYLON = {}));
  34500. //# sourceMappingURL=babylon.geometry.js.map
  34501. var BABYLON;
  34502. (function (BABYLON) {
  34503. var PostProcessManager = /** @class */ (function () {
  34504. function PostProcessManager(scene) {
  34505. this._vertexBuffers = {};
  34506. this._scene = scene;
  34507. }
  34508. PostProcessManager.prototype._prepareBuffers = function () {
  34509. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34510. return;
  34511. }
  34512. // VBO
  34513. var vertices = [];
  34514. vertices.push(1, 1);
  34515. vertices.push(-1, 1);
  34516. vertices.push(-1, -1);
  34517. vertices.push(1, -1);
  34518. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34519. this._buildIndexBuffer();
  34520. };
  34521. PostProcessManager.prototype._buildIndexBuffer = function () {
  34522. // Indices
  34523. var indices = [];
  34524. indices.push(0);
  34525. indices.push(1);
  34526. indices.push(2);
  34527. indices.push(0);
  34528. indices.push(2);
  34529. indices.push(3);
  34530. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34531. };
  34532. PostProcessManager.prototype._rebuild = function () {
  34533. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34534. if (!vb) {
  34535. return;
  34536. }
  34537. vb._rebuild();
  34538. this._buildIndexBuffer();
  34539. };
  34540. // Methods
  34541. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34542. if (sourceTexture === void 0) { sourceTexture = null; }
  34543. if (postProcesses === void 0) { postProcesses = null; }
  34544. var camera = this._scene.activeCamera;
  34545. if (!camera) {
  34546. return false;
  34547. }
  34548. var postProcesses = postProcesses || camera._postProcesses;
  34549. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34550. return false;
  34551. }
  34552. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34553. return true;
  34554. };
  34555. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34556. if (targetTexture === void 0) { targetTexture = null; }
  34557. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34558. var engine = this._scene.getEngine();
  34559. for (var index = 0; index < postProcesses.length; index++) {
  34560. if (index < postProcesses.length - 1) {
  34561. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34562. }
  34563. else {
  34564. if (targetTexture) {
  34565. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34566. }
  34567. else {
  34568. engine.restoreDefaultFramebuffer();
  34569. }
  34570. }
  34571. var pp = postProcesses[index];
  34572. var effect = pp.apply();
  34573. if (effect) {
  34574. pp.onBeforeRenderObservable.notifyObservers(effect);
  34575. // VBOs
  34576. this._prepareBuffers();
  34577. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34578. // Draw order
  34579. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34580. pp.onAfterRenderObservable.notifyObservers(effect);
  34581. }
  34582. }
  34583. // Restore depth buffer
  34584. engine.setDepthBuffer(true);
  34585. engine.setDepthWrite(true);
  34586. };
  34587. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34588. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34589. var camera = this._scene.activeCamera;
  34590. if (!camera) {
  34591. return;
  34592. }
  34593. postProcesses = postProcesses || camera._postProcesses;
  34594. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34595. return;
  34596. }
  34597. var engine = this._scene.getEngine();
  34598. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34599. if (index < len - 1) {
  34600. postProcesses[index + 1].activate(camera, targetTexture);
  34601. }
  34602. else {
  34603. if (targetTexture) {
  34604. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34605. }
  34606. else {
  34607. engine.restoreDefaultFramebuffer();
  34608. }
  34609. }
  34610. if (doNotPresent) {
  34611. break;
  34612. }
  34613. var pp = postProcesses[index];
  34614. var effect = pp.apply();
  34615. if (effect) {
  34616. pp.onBeforeRenderObservable.notifyObservers(effect);
  34617. // VBOs
  34618. this._prepareBuffers();
  34619. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34620. // Draw order
  34621. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34622. pp.onAfterRenderObservable.notifyObservers(effect);
  34623. }
  34624. }
  34625. // Restore states
  34626. engine.setDepthBuffer(true);
  34627. engine.setDepthWrite(true);
  34628. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34629. };
  34630. PostProcessManager.prototype.dispose = function () {
  34631. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34632. if (buffer) {
  34633. buffer.dispose();
  34634. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34635. }
  34636. if (this._indexBuffer) {
  34637. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34638. this._indexBuffer = null;
  34639. }
  34640. };
  34641. return PostProcessManager;
  34642. }());
  34643. BABYLON.PostProcessManager = PostProcessManager;
  34644. })(BABYLON || (BABYLON = {}));
  34645. //# sourceMappingURL=babylon.postProcessManager.js.map
  34646. var BABYLON;
  34647. (function (BABYLON) {
  34648. /**
  34649. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34650. */
  34651. var PerformanceMonitor = /** @class */ (function () {
  34652. /**
  34653. * constructor
  34654. * @param frameSampleSize The number of samples required to saturate the sliding window
  34655. */
  34656. function PerformanceMonitor(frameSampleSize) {
  34657. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34658. this._enabled = true;
  34659. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34660. }
  34661. /**
  34662. * Samples current frame
  34663. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34664. */
  34665. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34666. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34667. if (!this._enabled)
  34668. return;
  34669. if (this._lastFrameTimeMs != null) {
  34670. var dt = timeMs - this._lastFrameTimeMs;
  34671. this._rollingFrameTime.add(dt);
  34672. }
  34673. this._lastFrameTimeMs = timeMs;
  34674. };
  34675. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34676. /**
  34677. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34678. * @return Average frame time in milliseconds
  34679. */
  34680. get: function () {
  34681. return this._rollingFrameTime.average;
  34682. },
  34683. enumerable: true,
  34684. configurable: true
  34685. });
  34686. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34687. /**
  34688. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34689. * @return Frame time variance in milliseconds squared
  34690. */
  34691. get: function () {
  34692. return this._rollingFrameTime.variance;
  34693. },
  34694. enumerable: true,
  34695. configurable: true
  34696. });
  34697. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34698. /**
  34699. * Returns the frame time of the most recent frame
  34700. * @return Frame time in milliseconds
  34701. */
  34702. get: function () {
  34703. return this._rollingFrameTime.history(0);
  34704. },
  34705. enumerable: true,
  34706. configurable: true
  34707. });
  34708. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34709. /**
  34710. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34711. * @return Framerate in frames per second
  34712. */
  34713. get: function () {
  34714. return 1000.0 / this._rollingFrameTime.average;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34720. /**
  34721. * Returns the average framerate in frames per second using the most recent frame time
  34722. * @return Framerate in frames per second
  34723. */
  34724. get: function () {
  34725. var history = this._rollingFrameTime.history(0);
  34726. if (history === 0) {
  34727. return 0;
  34728. }
  34729. return 1000.0 / history;
  34730. },
  34731. enumerable: true,
  34732. configurable: true
  34733. });
  34734. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34735. /**
  34736. * Returns true if enough samples have been taken to completely fill the sliding window
  34737. * @return true if saturated
  34738. */
  34739. get: function () {
  34740. return this._rollingFrameTime.isSaturated();
  34741. },
  34742. enumerable: true,
  34743. configurable: true
  34744. });
  34745. /**
  34746. * Enables contributions to the sliding window sample set
  34747. */
  34748. PerformanceMonitor.prototype.enable = function () {
  34749. this._enabled = true;
  34750. };
  34751. /**
  34752. * Disables contributions to the sliding window sample set
  34753. * Samples will not be interpolated over the disabled period
  34754. */
  34755. PerformanceMonitor.prototype.disable = function () {
  34756. this._enabled = false;
  34757. //clear last sample to avoid interpolating over the disabled period when next enabled
  34758. this._lastFrameTimeMs = null;
  34759. };
  34760. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34761. /**
  34762. * Returns true if sampling is enabled
  34763. * @return true if enabled
  34764. */
  34765. get: function () {
  34766. return this._enabled;
  34767. },
  34768. enumerable: true,
  34769. configurable: true
  34770. });
  34771. /**
  34772. * Resets performance monitor
  34773. */
  34774. PerformanceMonitor.prototype.reset = function () {
  34775. //clear last sample to avoid interpolating over the disabled period when next enabled
  34776. this._lastFrameTimeMs = null;
  34777. //wipe record
  34778. this._rollingFrameTime.reset();
  34779. };
  34780. return PerformanceMonitor;
  34781. }());
  34782. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34783. /**
  34784. * RollingAverage
  34785. *
  34786. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34787. */
  34788. var RollingAverage = /** @class */ (function () {
  34789. /**
  34790. * constructor
  34791. * @param length The number of samples required to saturate the sliding window
  34792. */
  34793. function RollingAverage(length) {
  34794. this._samples = new Array(length);
  34795. this.reset();
  34796. }
  34797. /**
  34798. * Adds a sample to the sample set
  34799. * @param v The sample value
  34800. */
  34801. RollingAverage.prototype.add = function (v) {
  34802. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34803. var delta;
  34804. //we need to check if we've already wrapped round
  34805. if (this.isSaturated()) {
  34806. //remove bottom of stack from mean
  34807. var bottomValue = this._samples[this._pos];
  34808. delta = bottomValue - this.average;
  34809. this.average -= delta / (this._sampleCount - 1);
  34810. this._m2 -= delta * (bottomValue - this.average);
  34811. }
  34812. else {
  34813. this._sampleCount++;
  34814. }
  34815. //add new value to mean
  34816. delta = v - this.average;
  34817. this.average += delta / (this._sampleCount);
  34818. this._m2 += delta * (v - this.average);
  34819. //set the new variance
  34820. this.variance = this._m2 / (this._sampleCount - 1);
  34821. this._samples[this._pos] = v;
  34822. this._pos++;
  34823. this._pos %= this._samples.length; //positive wrap around
  34824. };
  34825. /**
  34826. * Returns previously added values or null if outside of history or outside the sliding window domain
  34827. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34828. * @return Value previously recorded with add() or null if outside of range
  34829. */
  34830. RollingAverage.prototype.history = function (i) {
  34831. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34832. return 0;
  34833. }
  34834. var i0 = this._wrapPosition(this._pos - 1.0);
  34835. return this._samples[this._wrapPosition(i0 - i)];
  34836. };
  34837. /**
  34838. * Returns true if enough samples have been taken to completely fill the sliding window
  34839. * @return true if sample-set saturated
  34840. */
  34841. RollingAverage.prototype.isSaturated = function () {
  34842. return this._sampleCount >= this._samples.length;
  34843. };
  34844. /**
  34845. * Resets the rolling average (equivalent to 0 samples taken so far)
  34846. */
  34847. RollingAverage.prototype.reset = function () {
  34848. this.average = 0;
  34849. this.variance = 0;
  34850. this._sampleCount = 0;
  34851. this._pos = 0;
  34852. this._m2 = 0;
  34853. };
  34854. /**
  34855. * Wraps a value around the sample range boundaries
  34856. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34857. * @return Wrapped position in sample range
  34858. */
  34859. RollingAverage.prototype._wrapPosition = function (i) {
  34860. var max = this._samples.length;
  34861. return ((i % max) + max) % max;
  34862. };
  34863. return RollingAverage;
  34864. }());
  34865. BABYLON.RollingAverage = RollingAverage;
  34866. })(BABYLON || (BABYLON = {}));
  34867. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34868. var BABYLON;
  34869. (function (BABYLON) {
  34870. /**
  34871. * This groups together the common properties used for image processing either in direct forward pass
  34872. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34873. * or not.
  34874. */
  34875. var ImageProcessingConfiguration = /** @class */ (function () {
  34876. function ImageProcessingConfiguration() {
  34877. /**
  34878. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34879. */
  34880. this.colorCurves = new BABYLON.ColorCurves();
  34881. this._colorCurvesEnabled = false;
  34882. this._colorGradingEnabled = false;
  34883. this._colorGradingWithGreenDepth = true;
  34884. this._colorGradingBGR = true;
  34885. this._exposure = 1.0;
  34886. this._toneMappingEnabled = false;
  34887. this._contrast = 1.0;
  34888. /**
  34889. * Vignette stretch size.
  34890. */
  34891. this.vignetteStretch = 0;
  34892. /**
  34893. * Vignette centre X Offset.
  34894. */
  34895. this.vignetteCentreX = 0;
  34896. /**
  34897. * Vignette centre Y Offset.
  34898. */
  34899. this.vignetteCentreY = 0;
  34900. /**
  34901. * Vignette weight or intensity of the vignette effect.
  34902. */
  34903. this.vignetteWeight = 1.5;
  34904. /**
  34905. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34906. * if vignetteEnabled is set to true.
  34907. */
  34908. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34909. /**
  34910. * Camera field of view used by the Vignette effect.
  34911. */
  34912. this.vignetteCameraFov = 0.5;
  34913. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34914. this._vignetteEnabled = false;
  34915. this._applyByPostProcess = false;
  34916. this._isEnabled = true;
  34917. /**
  34918. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34919. * @type {BABYLON.Observable}
  34920. */
  34921. this.onUpdateParameters = new BABYLON.Observable();
  34922. }
  34923. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34924. /**
  34925. * Gets wether the color curves effect is enabled.
  34926. */
  34927. get: function () {
  34928. return this._colorCurvesEnabled;
  34929. },
  34930. /**
  34931. * Sets wether the color curves effect is enabled.
  34932. */
  34933. set: function (value) {
  34934. if (this._colorCurvesEnabled === value) {
  34935. return;
  34936. }
  34937. this._colorCurvesEnabled = value;
  34938. this._updateParameters();
  34939. },
  34940. enumerable: true,
  34941. configurable: true
  34942. });
  34943. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34944. /**
  34945. * Gets wether the color grading effect is enabled.
  34946. */
  34947. get: function () {
  34948. return this._colorGradingEnabled;
  34949. },
  34950. /**
  34951. * Sets wether the color grading effect is enabled.
  34952. */
  34953. set: function (value) {
  34954. if (this._colorGradingEnabled === value) {
  34955. return;
  34956. }
  34957. this._colorGradingEnabled = value;
  34958. this._updateParameters();
  34959. },
  34960. enumerable: true,
  34961. configurable: true
  34962. });
  34963. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34964. /**
  34965. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34966. */
  34967. get: function () {
  34968. return this._colorGradingWithGreenDepth;
  34969. },
  34970. /**
  34971. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34972. */
  34973. set: function (value) {
  34974. if (this._colorGradingWithGreenDepth === value) {
  34975. return;
  34976. }
  34977. this._colorGradingWithGreenDepth = value;
  34978. this._updateParameters();
  34979. },
  34980. enumerable: true,
  34981. configurable: true
  34982. });
  34983. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34984. /**
  34985. * Gets wether the color grading texture contains BGR values.
  34986. */
  34987. get: function () {
  34988. return this._colorGradingBGR;
  34989. },
  34990. /**
  34991. * Sets wether the color grading texture contains BGR values.
  34992. */
  34993. set: function (value) {
  34994. if (this._colorGradingBGR === value) {
  34995. return;
  34996. }
  34997. this._colorGradingBGR = value;
  34998. this._updateParameters();
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  35004. /**
  35005. * Gets the Exposure used in the effect.
  35006. */
  35007. get: function () {
  35008. return this._exposure;
  35009. },
  35010. /**
  35011. * Sets the Exposure used in the effect.
  35012. */
  35013. set: function (value) {
  35014. if (this._exposure === value) {
  35015. return;
  35016. }
  35017. this._exposure = value;
  35018. this._updateParameters();
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  35024. /**
  35025. * Gets wether the tone mapping effect is enabled.
  35026. */
  35027. get: function () {
  35028. return this._toneMappingEnabled;
  35029. },
  35030. /**
  35031. * Sets wether the tone mapping effect is enabled.
  35032. */
  35033. set: function (value) {
  35034. if (this._toneMappingEnabled === value) {
  35035. return;
  35036. }
  35037. this._toneMappingEnabled = value;
  35038. this._updateParameters();
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  35044. /**
  35045. * Gets the contrast used in the effect.
  35046. */
  35047. get: function () {
  35048. return this._contrast;
  35049. },
  35050. /**
  35051. * Sets the contrast used in the effect.
  35052. */
  35053. set: function (value) {
  35054. if (this._contrast === value) {
  35055. return;
  35056. }
  35057. this._contrast = value;
  35058. this._updateParameters();
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  35064. /**
  35065. * Gets the vignette blend mode allowing different kind of effect.
  35066. */
  35067. get: function () {
  35068. return this._vignetteBlendMode;
  35069. },
  35070. /**
  35071. * Sets the vignette blend mode allowing different kind of effect.
  35072. */
  35073. set: function (value) {
  35074. if (this._vignetteBlendMode === value) {
  35075. return;
  35076. }
  35077. this._vignetteBlendMode = value;
  35078. this._updateParameters();
  35079. },
  35080. enumerable: true,
  35081. configurable: true
  35082. });
  35083. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  35084. /**
  35085. * Gets wether the vignette effect is enabled.
  35086. */
  35087. get: function () {
  35088. return this._vignetteEnabled;
  35089. },
  35090. /**
  35091. * Sets wether the vignette effect is enabled.
  35092. */
  35093. set: function (value) {
  35094. if (this._vignetteEnabled === value) {
  35095. return;
  35096. }
  35097. this._vignetteEnabled = value;
  35098. this._updateParameters();
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  35104. /**
  35105. * Gets wether the image processing is applied through a post process or not.
  35106. */
  35107. get: function () {
  35108. return this._applyByPostProcess;
  35109. },
  35110. /**
  35111. * Sets wether the image processing is applied through a post process or not.
  35112. */
  35113. set: function (value) {
  35114. if (this._applyByPostProcess === value) {
  35115. return;
  35116. }
  35117. this._applyByPostProcess = value;
  35118. this._updateParameters();
  35119. },
  35120. enumerable: true,
  35121. configurable: true
  35122. });
  35123. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  35124. /**
  35125. * Gets wether the image processing is enabled or not.
  35126. */
  35127. get: function () {
  35128. return this._isEnabled;
  35129. },
  35130. /**
  35131. * Sets wether the image processing is enabled or not.
  35132. */
  35133. set: function (value) {
  35134. if (this._isEnabled === value) {
  35135. return;
  35136. }
  35137. this._isEnabled = value;
  35138. this._updateParameters();
  35139. },
  35140. enumerable: true,
  35141. configurable: true
  35142. });
  35143. /**
  35144. * Method called each time the image processing information changes requires to recompile the effect.
  35145. */
  35146. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35147. this.onUpdateParameters.notifyObservers(this);
  35148. };
  35149. ImageProcessingConfiguration.prototype.getClassName = function () {
  35150. return "ImageProcessingConfiguration";
  35151. };
  35152. /**
  35153. * Prepare the list of uniforms associated with the Image Processing effects.
  35154. * @param uniformsList The list of uniforms used in the effect
  35155. * @param defines the list of defines currently in use
  35156. */
  35157. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35158. if (defines.EXPOSURE) {
  35159. uniforms.push("exposureLinear");
  35160. }
  35161. if (defines.CONTRAST) {
  35162. uniforms.push("contrast");
  35163. }
  35164. if (defines.COLORGRADING) {
  35165. uniforms.push("colorTransformSettings");
  35166. }
  35167. if (defines.VIGNETTE) {
  35168. uniforms.push("vInverseScreenSize");
  35169. uniforms.push("vignetteSettings1");
  35170. uniforms.push("vignetteSettings2");
  35171. }
  35172. if (defines.COLORCURVES) {
  35173. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35174. }
  35175. };
  35176. /**
  35177. * Prepare the list of samplers associated with the Image Processing effects.
  35178. * @param uniformsList The list of uniforms used in the effect
  35179. * @param defines the list of defines currently in use
  35180. */
  35181. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35182. if (defines.COLORGRADING) {
  35183. samplersList.push("txColorTransform");
  35184. }
  35185. };
  35186. /**
  35187. * Prepare the list of defines associated to the shader.
  35188. * @param defines the list of defines to complete
  35189. */
  35190. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35191. if (forPostProcess === void 0) { forPostProcess = false; }
  35192. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35193. defines.VIGNETTE = false;
  35194. defines.TONEMAPPING = false;
  35195. defines.CONTRAST = false;
  35196. defines.EXPOSURE = false;
  35197. defines.COLORCURVES = false;
  35198. defines.COLORGRADING = false;
  35199. defines.COLORGRADING3D = false;
  35200. defines.IMAGEPROCESSING = false;
  35201. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35202. return;
  35203. }
  35204. defines.VIGNETTE = this.vignetteEnabled;
  35205. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35206. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35207. defines.TONEMAPPING = this.toneMappingEnabled;
  35208. defines.CONTRAST = (this.contrast !== 1.0);
  35209. defines.EXPOSURE = (this.exposure !== 1.0);
  35210. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35211. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35212. if (defines.COLORGRADING) {
  35213. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35214. }
  35215. else {
  35216. defines.COLORGRADING3D = false;
  35217. }
  35218. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35219. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35220. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35221. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35222. };
  35223. /**
  35224. * Returns true if all the image processing information are ready.
  35225. */
  35226. ImageProcessingConfiguration.prototype.isReady = function () {
  35227. // Color Grading texure can not be none blocking.
  35228. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35229. };
  35230. /**
  35231. * Binds the image processing to the shader.
  35232. * @param effect The effect to bind to
  35233. */
  35234. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35235. if (aspectRatio === void 0) { aspectRatio = 1; }
  35236. // Color Curves
  35237. if (this._colorCurvesEnabled && this.colorCurves) {
  35238. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35239. }
  35240. // Vignette
  35241. if (this._vignetteEnabled) {
  35242. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35243. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35244. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35245. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35246. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35247. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35248. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35249. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35250. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35251. var vignettePower = -2.0 * this.vignetteWeight;
  35252. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35253. }
  35254. // Exposure
  35255. effect.setFloat("exposureLinear", this.exposure);
  35256. // Contrast
  35257. effect.setFloat("contrast", this.contrast);
  35258. // Color transform settings
  35259. if (this.colorGradingTexture) {
  35260. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35261. var textureSize = this.colorGradingTexture.getSize().height;
  35262. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35263. 0.5 / textureSize, // textureOffset
  35264. textureSize, // textureSize
  35265. this.colorGradingTexture.level // weight
  35266. );
  35267. }
  35268. };
  35269. /**
  35270. * Clones the current image processing instance.
  35271. * @return The cloned image processing
  35272. */
  35273. ImageProcessingConfiguration.prototype.clone = function () {
  35274. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35275. };
  35276. /**
  35277. * Serializes the current image processing instance to a json representation.
  35278. * @return a JSON representation
  35279. */
  35280. ImageProcessingConfiguration.prototype.serialize = function () {
  35281. return BABYLON.SerializationHelper.Serialize(this);
  35282. };
  35283. /**
  35284. * Parses the image processing from a json representation.
  35285. * @param source the JSON source to parse
  35286. * @return The parsed image processing
  35287. */
  35288. ImageProcessingConfiguration.Parse = function (source) {
  35289. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35290. };
  35291. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35292. /**
  35293. * Used to apply the vignette as a mix with the pixel color.
  35294. */
  35295. get: function () {
  35296. return this._VIGNETTEMODE_MULTIPLY;
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35302. /**
  35303. * Used to apply the vignette as a replacement of the pixel color.
  35304. */
  35305. get: function () {
  35306. return this._VIGNETTEMODE_OPAQUE;
  35307. },
  35308. enumerable: true,
  35309. configurable: true
  35310. });
  35311. // Static constants associated to the image processing.
  35312. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35313. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35314. __decorate([
  35315. BABYLON.serializeAsColorCurves()
  35316. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35317. __decorate([
  35318. BABYLON.serialize()
  35319. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35320. __decorate([
  35321. BABYLON.serializeAsTexture()
  35322. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35323. __decorate([
  35324. BABYLON.serialize()
  35325. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35326. __decorate([
  35327. BABYLON.serialize()
  35328. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35329. __decorate([
  35330. BABYLON.serialize()
  35331. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35332. __decorate([
  35333. BABYLON.serialize()
  35334. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35335. __decorate([
  35336. BABYLON.serialize()
  35337. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35338. __decorate([
  35339. BABYLON.serialize()
  35340. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35341. __decorate([
  35342. BABYLON.serialize()
  35343. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35344. __decorate([
  35345. BABYLON.serialize()
  35346. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35347. __decorate([
  35348. BABYLON.serialize()
  35349. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35350. __decorate([
  35351. BABYLON.serialize()
  35352. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35353. __decorate([
  35354. BABYLON.serializeAsColor4()
  35355. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35356. __decorate([
  35357. BABYLON.serialize()
  35358. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35359. __decorate([
  35360. BABYLON.serialize()
  35361. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35362. __decorate([
  35363. BABYLON.serialize()
  35364. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35365. __decorate([
  35366. BABYLON.serialize()
  35367. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35368. __decorate([
  35369. BABYLON.serialize()
  35370. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35371. return ImageProcessingConfiguration;
  35372. }());
  35373. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35374. })(BABYLON || (BABYLON = {}));
  35375. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35376. var BABYLON;
  35377. (function (BABYLON) {
  35378. /**
  35379. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35380. * It can help converting any input color in a desired output one. This can then be used to create effects
  35381. * from sepia, black and white to sixties or futuristic rendering...
  35382. *
  35383. * The only supported format is currently 3dl.
  35384. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35385. */
  35386. var ColorGradingTexture = /** @class */ (function (_super) {
  35387. __extends(ColorGradingTexture, _super);
  35388. /**
  35389. * Instantiates a ColorGradingTexture from the following parameters.
  35390. *
  35391. * @param url The location of the color gradind data (currently only supporting 3dl)
  35392. * @param scene The scene the texture will be used in
  35393. */
  35394. function ColorGradingTexture(url, scene) {
  35395. var _this = _super.call(this, scene) || this;
  35396. if (!url) {
  35397. return _this;
  35398. }
  35399. _this._engine = scene.getEngine();
  35400. _this._textureMatrix = BABYLON.Matrix.Identity();
  35401. _this.name = url;
  35402. _this.url = url;
  35403. _this.hasAlpha = false;
  35404. _this.isCube = false;
  35405. _this.is3D = _this._engine.webGLVersion > 1;
  35406. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35407. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35408. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35409. _this.anisotropicFilteringLevel = 1;
  35410. _this._texture = _this._getFromCache(url, true);
  35411. if (!_this._texture) {
  35412. if (!scene.useDelayedTextureLoading) {
  35413. _this.loadTexture();
  35414. }
  35415. else {
  35416. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35417. }
  35418. }
  35419. return _this;
  35420. }
  35421. /**
  35422. * Returns the texture matrix used in most of the material.
  35423. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35424. */
  35425. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35426. return this._textureMatrix;
  35427. };
  35428. /**
  35429. * Occurs when the file being loaded is a .3dl LUT file.
  35430. */
  35431. ColorGradingTexture.prototype.load3dlTexture = function () {
  35432. var engine = this._engine;
  35433. var texture;
  35434. if (engine.webGLVersion === 1) {
  35435. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35436. }
  35437. else {
  35438. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35439. }
  35440. this._texture = texture;
  35441. var callback = function (text) {
  35442. if (typeof text !== "string") {
  35443. return;
  35444. }
  35445. var data = null;
  35446. var tempData = null;
  35447. var line;
  35448. var lines = text.split('\n');
  35449. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35450. var maxColor = 0;
  35451. for (var i = 0; i < lines.length; i++) {
  35452. line = lines[i];
  35453. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35454. continue;
  35455. if (line.indexOf('#') === 0)
  35456. continue;
  35457. var words = line.split(" ");
  35458. if (size === 0) {
  35459. // Number of space + one
  35460. size = words.length;
  35461. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35462. tempData = new Float32Array(size * size * size * 4);
  35463. continue;
  35464. }
  35465. if (size != 0) {
  35466. var r = Math.max(parseInt(words[0]), 0);
  35467. var g = Math.max(parseInt(words[1]), 0);
  35468. var b = Math.max(parseInt(words[2]), 0);
  35469. maxColor = Math.max(r, maxColor);
  35470. maxColor = Math.max(g, maxColor);
  35471. maxColor = Math.max(b, maxColor);
  35472. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35473. if (tempData) {
  35474. tempData[pixelStorageIndex + 0] = r;
  35475. tempData[pixelStorageIndex + 1] = g;
  35476. tempData[pixelStorageIndex + 2] = b;
  35477. }
  35478. pixelIndexSlice++;
  35479. if (pixelIndexSlice % size == 0) {
  35480. pixelIndexH++;
  35481. pixelIndexSlice = 0;
  35482. if (pixelIndexH % size == 0) {
  35483. pixelIndexW++;
  35484. pixelIndexH = 0;
  35485. }
  35486. }
  35487. }
  35488. }
  35489. if (tempData && data) {
  35490. for (var i = 0; i < tempData.length; i++) {
  35491. if (i > 0 && (i + 1) % 4 === 0) {
  35492. data[i] = 255;
  35493. }
  35494. else {
  35495. var value = tempData[i];
  35496. data[i] = (value / maxColor * 255);
  35497. }
  35498. }
  35499. }
  35500. if (texture.is3D) {
  35501. texture.updateSize(size, size, size);
  35502. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35503. }
  35504. else {
  35505. texture.updateSize(size * size, size);
  35506. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35507. }
  35508. };
  35509. var scene = this.getScene();
  35510. if (scene) {
  35511. scene._loadFile(this.url, callback);
  35512. }
  35513. else {
  35514. this._engine._loadFile(this.url, callback);
  35515. }
  35516. return this._texture;
  35517. };
  35518. /**
  35519. * Starts the loading process of the texture.
  35520. */
  35521. ColorGradingTexture.prototype.loadTexture = function () {
  35522. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35523. this.load3dlTexture();
  35524. }
  35525. };
  35526. /**
  35527. * Clones the color gradind texture.
  35528. */
  35529. ColorGradingTexture.prototype.clone = function () {
  35530. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35531. // Base texture
  35532. newTexture.level = this.level;
  35533. return newTexture;
  35534. };
  35535. /**
  35536. * Called during delayed load for textures.
  35537. */
  35538. ColorGradingTexture.prototype.delayLoad = function () {
  35539. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35540. return;
  35541. }
  35542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35543. this._texture = this._getFromCache(this.url, true);
  35544. if (!this._texture) {
  35545. this.loadTexture();
  35546. }
  35547. };
  35548. /**
  35549. * Parses a color grading texture serialized by Babylon.
  35550. * @param parsedTexture The texture information being parsedTexture
  35551. * @param scene The scene to load the texture in
  35552. * @param rootUrl The root url of the data assets to load
  35553. * @return A color gradind texture
  35554. */
  35555. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35556. var texture = null;
  35557. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35558. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35559. texture.name = parsedTexture.name;
  35560. texture.level = parsedTexture.level;
  35561. }
  35562. return texture;
  35563. };
  35564. /**
  35565. * Serializes the LUT texture to json format.
  35566. */
  35567. ColorGradingTexture.prototype.serialize = function () {
  35568. if (!this.name) {
  35569. return null;
  35570. }
  35571. var serializationObject = {};
  35572. serializationObject.name = this.name;
  35573. serializationObject.level = this.level;
  35574. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35575. return serializationObject;
  35576. };
  35577. /**
  35578. * Empty line regex stored for GC.
  35579. */
  35580. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35581. return ColorGradingTexture;
  35582. }(BABYLON.BaseTexture));
  35583. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35584. })(BABYLON || (BABYLON = {}));
  35585. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35586. var BABYLON;
  35587. (function (BABYLON) {
  35588. /**
  35589. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35590. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35591. * 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;
  35592. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35593. */
  35594. var ColorCurves = /** @class */ (function () {
  35595. function ColorCurves() {
  35596. this._dirty = true;
  35597. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35598. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35599. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35600. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35601. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35602. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35603. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35604. this._globalHue = 30;
  35605. this._globalDensity = 0;
  35606. this._globalSaturation = 0;
  35607. this._globalExposure = 0;
  35608. this._highlightsHue = 30;
  35609. this._highlightsDensity = 0;
  35610. this._highlightsSaturation = 0;
  35611. this._highlightsExposure = 0;
  35612. this._midtonesHue = 30;
  35613. this._midtonesDensity = 0;
  35614. this._midtonesSaturation = 0;
  35615. this._midtonesExposure = 0;
  35616. this._shadowsHue = 30;
  35617. this._shadowsDensity = 0;
  35618. this._shadowsSaturation = 0;
  35619. this._shadowsExposure = 0;
  35620. }
  35621. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35622. /**
  35623. * Gets the global Hue value.
  35624. * 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).
  35625. */
  35626. get: function () {
  35627. return this._globalHue;
  35628. },
  35629. /**
  35630. * Sets the global Hue value.
  35631. * 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).
  35632. */
  35633. set: function (value) {
  35634. this._globalHue = value;
  35635. this._dirty = true;
  35636. },
  35637. enumerable: true,
  35638. configurable: true
  35639. });
  35640. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35641. /**
  35642. * Gets the global Density value.
  35643. * 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.
  35644. * Values less than zero provide a filter of opposite hue.
  35645. */
  35646. get: function () {
  35647. return this._globalDensity;
  35648. },
  35649. /**
  35650. * Sets the global Density value.
  35651. * 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.
  35652. * Values less than zero provide a filter of opposite hue.
  35653. */
  35654. set: function (value) {
  35655. this._globalDensity = value;
  35656. this._dirty = true;
  35657. },
  35658. enumerable: true,
  35659. configurable: true
  35660. });
  35661. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35662. /**
  35663. * Gets the global Saturation value.
  35664. * 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.
  35665. */
  35666. get: function () {
  35667. return this._globalSaturation;
  35668. },
  35669. /**
  35670. * Sets the global Saturation value.
  35671. * 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.
  35672. */
  35673. set: function (value) {
  35674. this._globalSaturation = value;
  35675. this._dirty = true;
  35676. },
  35677. enumerable: true,
  35678. configurable: true
  35679. });
  35680. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35681. /**
  35682. * Gets the highlights Hue value.
  35683. * 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).
  35684. */
  35685. get: function () {
  35686. return this._highlightsHue;
  35687. },
  35688. /**
  35689. * Sets the highlights Hue value.
  35690. * 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).
  35691. */
  35692. set: function (value) {
  35693. this._highlightsHue = value;
  35694. this._dirty = true;
  35695. },
  35696. enumerable: true,
  35697. configurable: true
  35698. });
  35699. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35700. /**
  35701. * Gets the highlights Density value.
  35702. * 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.
  35703. * Values less than zero provide a filter of opposite hue.
  35704. */
  35705. get: function () {
  35706. return this._highlightsDensity;
  35707. },
  35708. /**
  35709. * Sets the highlights Density value.
  35710. * 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.
  35711. * Values less than zero provide a filter of opposite hue.
  35712. */
  35713. set: function (value) {
  35714. this._highlightsDensity = value;
  35715. this._dirty = true;
  35716. },
  35717. enumerable: true,
  35718. configurable: true
  35719. });
  35720. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35721. /**
  35722. * Gets the highlights Saturation value.
  35723. * 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.
  35724. */
  35725. get: function () {
  35726. return this._highlightsSaturation;
  35727. },
  35728. /**
  35729. * Sets the highlights Saturation value.
  35730. * 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.
  35731. */
  35732. set: function (value) {
  35733. this._highlightsSaturation = value;
  35734. this._dirty = true;
  35735. },
  35736. enumerable: true,
  35737. configurable: true
  35738. });
  35739. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35740. /**
  35741. * Gets the highlights Exposure value.
  35742. * 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.
  35743. */
  35744. get: function () {
  35745. return this._highlightsExposure;
  35746. },
  35747. /**
  35748. * Sets the highlights Exposure value.
  35749. * 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.
  35750. */
  35751. set: function (value) {
  35752. this._highlightsExposure = value;
  35753. this._dirty = true;
  35754. },
  35755. enumerable: true,
  35756. configurable: true
  35757. });
  35758. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35759. /**
  35760. * Gets the midtones Hue value.
  35761. * 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).
  35762. */
  35763. get: function () {
  35764. return this._midtonesHue;
  35765. },
  35766. /**
  35767. * Sets the midtones Hue value.
  35768. * 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).
  35769. */
  35770. set: function (value) {
  35771. this._midtonesHue = value;
  35772. this._dirty = true;
  35773. },
  35774. enumerable: true,
  35775. configurable: true
  35776. });
  35777. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35778. /**
  35779. * Gets the midtones Density value.
  35780. * 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.
  35781. * Values less than zero provide a filter of opposite hue.
  35782. */
  35783. get: function () {
  35784. return this._midtonesDensity;
  35785. },
  35786. /**
  35787. * Sets the midtones Density value.
  35788. * 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.
  35789. * Values less than zero provide a filter of opposite hue.
  35790. */
  35791. set: function (value) {
  35792. this._midtonesDensity = value;
  35793. this._dirty = true;
  35794. },
  35795. enumerable: true,
  35796. configurable: true
  35797. });
  35798. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35799. /**
  35800. * Gets the midtones Saturation value.
  35801. * 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.
  35802. */
  35803. get: function () {
  35804. return this._midtonesSaturation;
  35805. },
  35806. /**
  35807. * Sets the midtones Saturation value.
  35808. * 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.
  35809. */
  35810. set: function (value) {
  35811. this._midtonesSaturation = value;
  35812. this._dirty = true;
  35813. },
  35814. enumerable: true,
  35815. configurable: true
  35816. });
  35817. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35818. /**
  35819. * Gets the midtones Exposure value.
  35820. * 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.
  35821. */
  35822. get: function () {
  35823. return this._midtonesExposure;
  35824. },
  35825. /**
  35826. * Sets the midtones Exposure value.
  35827. * 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.
  35828. */
  35829. set: function (value) {
  35830. this._midtonesExposure = value;
  35831. this._dirty = true;
  35832. },
  35833. enumerable: true,
  35834. configurable: true
  35835. });
  35836. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35837. /**
  35838. * Gets the shadows Hue value.
  35839. * 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).
  35840. */
  35841. get: function () {
  35842. return this._shadowsHue;
  35843. },
  35844. /**
  35845. * Sets the shadows Hue value.
  35846. * 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).
  35847. */
  35848. set: function (value) {
  35849. this._shadowsHue = value;
  35850. this._dirty = true;
  35851. },
  35852. enumerable: true,
  35853. configurable: true
  35854. });
  35855. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35856. /**
  35857. * Gets the shadows Density value.
  35858. * 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.
  35859. * Values less than zero provide a filter of opposite hue.
  35860. */
  35861. get: function () {
  35862. return this._shadowsDensity;
  35863. },
  35864. /**
  35865. * Sets the shadows Density value.
  35866. * 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.
  35867. * Values less than zero provide a filter of opposite hue.
  35868. */
  35869. set: function (value) {
  35870. this._shadowsDensity = value;
  35871. this._dirty = true;
  35872. },
  35873. enumerable: true,
  35874. configurable: true
  35875. });
  35876. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35877. /**
  35878. * Gets the shadows Saturation value.
  35879. * 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.
  35880. */
  35881. get: function () {
  35882. return this._shadowsSaturation;
  35883. },
  35884. /**
  35885. * Sets the shadows Saturation value.
  35886. * 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.
  35887. */
  35888. set: function (value) {
  35889. this._shadowsSaturation = value;
  35890. this._dirty = true;
  35891. },
  35892. enumerable: true,
  35893. configurable: true
  35894. });
  35895. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35896. /**
  35897. * Gets the shadows Exposure value.
  35898. * 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.
  35899. */
  35900. get: function () {
  35901. return this._shadowsExposure;
  35902. },
  35903. /**
  35904. * Sets the shadows Exposure value.
  35905. * 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.
  35906. */
  35907. set: function (value) {
  35908. this._shadowsExposure = value;
  35909. this._dirty = true;
  35910. },
  35911. enumerable: true,
  35912. configurable: true
  35913. });
  35914. ColorCurves.prototype.getClassName = function () {
  35915. return "ColorCurves";
  35916. };
  35917. /**
  35918. * Binds the color curves to the shader.
  35919. * @param colorCurves The color curve to bind
  35920. * @param effect The effect to bind to
  35921. */
  35922. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35923. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35924. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35925. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35926. if (colorCurves._dirty) {
  35927. colorCurves._dirty = false;
  35928. // Fill in global info.
  35929. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35930. // Compute highlights info.
  35931. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35932. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35933. // Compute midtones info.
  35934. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35935. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35936. // Compute shadows info.
  35937. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35938. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35939. // Compute deltas (neutral is midtones).
  35940. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35941. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35942. }
  35943. if (effect) {
  35944. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35945. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35946. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35947. }
  35948. };
  35949. /**
  35950. * Prepare the list of uniforms associated with the ColorCurves effects.
  35951. * @param uniformsList The list of uniforms used in the effect
  35952. */
  35953. ColorCurves.PrepareUniforms = function (uniformsList) {
  35954. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35955. };
  35956. /**
  35957. * Returns color grading data based on a hue, density, saturation and exposure value.
  35958. * @param filterHue The hue of the color filter.
  35959. * @param filterDensity The density of the color filter.
  35960. * @param saturation The saturation.
  35961. * @param exposure The exposure.
  35962. * @param result The result data container.
  35963. */
  35964. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35965. if (hue == null) {
  35966. return;
  35967. }
  35968. hue = ColorCurves.clamp(hue, 0, 360);
  35969. density = ColorCurves.clamp(density, -100, 100);
  35970. saturation = ColorCurves.clamp(saturation, -100, 100);
  35971. exposure = ColorCurves.clamp(exposure, -100, 100);
  35972. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35973. // so that the maximum filter density is only 50% control. This provides fine control
  35974. // for small values and reasonable range.
  35975. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35976. density *= 0.5;
  35977. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35978. if (density < 0) {
  35979. density *= -1;
  35980. hue = (hue + 180) % 360;
  35981. }
  35982. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35983. result.scaleToRef(2, result);
  35984. result.a = 1 + 0.01 * saturation;
  35985. };
  35986. /**
  35987. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35988. * @param value The input slider value in range [-100,100].
  35989. * @returns Adjusted value.
  35990. */
  35991. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35992. value /= 100;
  35993. var x = Math.abs(value);
  35994. x = Math.pow(x, 2);
  35995. if (value < 0) {
  35996. x *= -1;
  35997. }
  35998. x *= 100;
  35999. return x;
  36000. };
  36001. /**
  36002. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  36003. * @param hue The hue (H) input.
  36004. * @param saturation The saturation (S) input.
  36005. * @param brightness The brightness (B) input.
  36006. * @result An RGBA color represented as Vector4.
  36007. */
  36008. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  36009. var h = ColorCurves.clamp(hue, 0, 360);
  36010. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  36011. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  36012. if (s === 0) {
  36013. result.r = v;
  36014. result.g = v;
  36015. result.b = v;
  36016. }
  36017. else {
  36018. // sector 0 to 5
  36019. h /= 60;
  36020. var i = Math.floor(h);
  36021. // fractional part of h
  36022. var f = h - i;
  36023. var p = v * (1 - s);
  36024. var q = v * (1 - s * f);
  36025. var t = v * (1 - s * (1 - f));
  36026. switch (i) {
  36027. case 0:
  36028. result.r = v;
  36029. result.g = t;
  36030. result.b = p;
  36031. break;
  36032. case 1:
  36033. result.r = q;
  36034. result.g = v;
  36035. result.b = p;
  36036. break;
  36037. case 2:
  36038. result.r = p;
  36039. result.g = v;
  36040. result.b = t;
  36041. break;
  36042. case 3:
  36043. result.r = p;
  36044. result.g = q;
  36045. result.b = v;
  36046. break;
  36047. case 4:
  36048. result.r = t;
  36049. result.g = p;
  36050. result.b = v;
  36051. break;
  36052. default:// case 5:
  36053. result.r = v;
  36054. result.g = p;
  36055. result.b = q;
  36056. break;
  36057. }
  36058. }
  36059. result.a = 1;
  36060. };
  36061. /**
  36062. * Returns a value clamped between min and max
  36063. * @param value The value to clamp
  36064. * @param min The minimum of value
  36065. * @param max The maximum of value
  36066. * @returns The clamped value.
  36067. */
  36068. ColorCurves.clamp = function (value, min, max) {
  36069. return Math.min(Math.max(value, min), max);
  36070. };
  36071. /**
  36072. * Clones the current color curve instance.
  36073. * @return The cloned curves
  36074. */
  36075. ColorCurves.prototype.clone = function () {
  36076. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  36077. };
  36078. /**
  36079. * Serializes the current color curve instance to a json representation.
  36080. * @return a JSON representation
  36081. */
  36082. ColorCurves.prototype.serialize = function () {
  36083. return BABYLON.SerializationHelper.Serialize(this);
  36084. };
  36085. /**
  36086. * Parses the color curve from a json representation.
  36087. * @param source the JSON source to parse
  36088. * @return The parsed curves
  36089. */
  36090. ColorCurves.Parse = function (source) {
  36091. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  36092. };
  36093. __decorate([
  36094. BABYLON.serialize()
  36095. ], ColorCurves.prototype, "_globalHue", void 0);
  36096. __decorate([
  36097. BABYLON.serialize()
  36098. ], ColorCurves.prototype, "_globalDensity", void 0);
  36099. __decorate([
  36100. BABYLON.serialize()
  36101. ], ColorCurves.prototype, "_globalSaturation", void 0);
  36102. __decorate([
  36103. BABYLON.serialize()
  36104. ], ColorCurves.prototype, "_globalExposure", void 0);
  36105. __decorate([
  36106. BABYLON.serialize()
  36107. ], ColorCurves.prototype, "_highlightsHue", void 0);
  36108. __decorate([
  36109. BABYLON.serialize()
  36110. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  36111. __decorate([
  36112. BABYLON.serialize()
  36113. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  36114. __decorate([
  36115. BABYLON.serialize()
  36116. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  36117. __decorate([
  36118. BABYLON.serialize()
  36119. ], ColorCurves.prototype, "_midtonesHue", void 0);
  36120. __decorate([
  36121. BABYLON.serialize()
  36122. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  36123. __decorate([
  36124. BABYLON.serialize()
  36125. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  36126. __decorate([
  36127. BABYLON.serialize()
  36128. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36129. return ColorCurves;
  36130. }());
  36131. BABYLON.ColorCurves = ColorCurves;
  36132. })(BABYLON || (BABYLON = {}));
  36133. //# sourceMappingURL=babylon.colorCurves.js.map
  36134. //# sourceMappingURL=babylon.behavior.js.map
  36135. var BABYLON;
  36136. (function (BABYLON) {
  36137. /**
  36138. * "Static Class" containing the most commonly used helper while dealing with material for
  36139. * rendering purpose.
  36140. *
  36141. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  36142. *
  36143. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  36144. */
  36145. var MaterialHelper = /** @class */ (function () {
  36146. function MaterialHelper() {
  36147. }
  36148. /**
  36149. * Bind the current view position to an effect.
  36150. * @param effect The effect to be bound
  36151. * @param scene The scene the eyes position is used from
  36152. */
  36153. MaterialHelper.BindEyePosition = function (effect, scene) {
  36154. if (scene._forcedViewPosition) {
  36155. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36156. return;
  36157. }
  36158. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36159. };
  36160. /**
  36161. * Helps preparing the defines values about the UVs in used in the effect.
  36162. * UVs are shared as much as we can accross chanels in the shaders.
  36163. * @param texture The texture we are preparing the UVs for
  36164. * @param defines The defines to update
  36165. * @param key The chanel key "diffuse", "specular"... used in the shader
  36166. */
  36167. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36168. defines._needUVs = true;
  36169. defines[key] = true;
  36170. if (texture.getTextureMatrix().isIdentity(true)) {
  36171. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36172. if (texture.coordinatesIndex === 0) {
  36173. defines["MAINUV1"] = true;
  36174. }
  36175. else {
  36176. defines["MAINUV2"] = true;
  36177. }
  36178. }
  36179. else {
  36180. defines[key + "DIRECTUV"] = 0;
  36181. }
  36182. };
  36183. /**
  36184. * Binds a texture matrix value to its corrsponding uniform
  36185. * @param texture The texture to bind the matrix for
  36186. * @param uniformBuffer The uniform buffer receivin the data
  36187. * @param key The chanel key "diffuse", "specular"... used in the shader
  36188. */
  36189. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36190. var matrix = texture.getTextureMatrix();
  36191. if (!matrix.isIdentity(true)) {
  36192. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36193. }
  36194. };
  36195. /**
  36196. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36197. * @param mesh defines the current mesh
  36198. * @param scene defines the current scene
  36199. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36200. * @param pointsCloud defines if point cloud rendering has to be turned on
  36201. * @param fogEnabled defines if fog has to be turned on
  36202. * @param alphaTest defines if alpha testing has to be turned on
  36203. * @param defines defines the current list of defines
  36204. */
  36205. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36206. if (defines._areMiscDirty) {
  36207. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36208. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36209. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36210. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36211. defines["ALPHATEST"] = alphaTest;
  36212. }
  36213. };
  36214. /**
  36215. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36216. * @param scene defines the current scene
  36217. * @param engine defines the current engine
  36218. * @param defines specifies the list of active defines
  36219. * @param useInstances defines if instances have to be turned on
  36220. */
  36221. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36222. var changed = false;
  36223. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36224. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36225. changed = true;
  36226. }
  36227. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36228. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36229. changed = true;
  36230. }
  36231. if (defines["INSTANCES"] !== useInstances) {
  36232. defines["INSTANCES"] = useInstances;
  36233. changed = true;
  36234. }
  36235. if (changed) {
  36236. defines.markAsUnprocessed();
  36237. }
  36238. };
  36239. /**
  36240. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  36241. * @param mesh The mesh containing the geometry data we will draw
  36242. * @param defines The defines to update
  36243. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  36244. * @param useBones Precise whether bones should be used or not (override mesh info)
  36245. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  36246. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  36247. * @returns false if defines are considered not dirty and have not been checked
  36248. */
  36249. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36250. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36251. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36252. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36253. return false;
  36254. }
  36255. defines._normals = defines._needNormals;
  36256. defines._uvs = defines._needUVs;
  36257. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36258. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36259. defines["TANGENT"] = true;
  36260. }
  36261. if (defines._needUVs) {
  36262. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36263. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36264. }
  36265. else {
  36266. defines["UV1"] = false;
  36267. defines["UV2"] = false;
  36268. }
  36269. if (useVertexColor) {
  36270. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36271. defines["VERTEXCOLOR"] = hasVertexColors;
  36272. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36273. }
  36274. if (useBones) {
  36275. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36276. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36277. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36278. }
  36279. else {
  36280. defines["NUM_BONE_INFLUENCERS"] = 0;
  36281. defines["BonesPerMesh"] = 0;
  36282. }
  36283. }
  36284. if (useMorphTargets) {
  36285. var manager = mesh.morphTargetManager;
  36286. if (manager) {
  36287. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36288. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36289. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36290. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36291. }
  36292. else {
  36293. defines["MORPHTARGETS_TANGENT"] = false;
  36294. defines["MORPHTARGETS_NORMAL"] = false;
  36295. defines["MORPHTARGETS"] = false;
  36296. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36297. }
  36298. }
  36299. return true;
  36300. };
  36301. /**
  36302. * Prepares the defines related to the light information passed in parameter
  36303. * @param scene The scene we are intending to draw
  36304. * @param mesh The mesh the effect is compiling for
  36305. * @param defines The defines to update
  36306. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  36307. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  36308. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  36309. * @returns true if normals will be required for the rest of the effect
  36310. */
  36311. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36312. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36313. if (disableLighting === void 0) { disableLighting = false; }
  36314. if (!defines._areLightsDirty) {
  36315. return defines._needNormals;
  36316. }
  36317. var lightIndex = 0;
  36318. var needNormals = false;
  36319. var needRebuild = false;
  36320. var lightmapMode = false;
  36321. var shadowEnabled = false;
  36322. var specularEnabled = false;
  36323. if (scene.lightsEnabled && !disableLighting) {
  36324. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36325. var light = _a[_i];
  36326. needNormals = true;
  36327. if (defines["LIGHT" + lightIndex] === undefined) {
  36328. needRebuild = true;
  36329. }
  36330. defines["LIGHT" + lightIndex] = true;
  36331. defines["SPOTLIGHT" + lightIndex] = false;
  36332. defines["HEMILIGHT" + lightIndex] = false;
  36333. defines["POINTLIGHT" + lightIndex] = false;
  36334. defines["DIRLIGHT" + lightIndex] = false;
  36335. var type;
  36336. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36337. type = "SPOTLIGHT" + lightIndex;
  36338. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = light.projectedLightTexture ? true : false;
  36339. }
  36340. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36341. type = "HEMILIGHT" + lightIndex;
  36342. }
  36343. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36344. type = "POINTLIGHT" + lightIndex;
  36345. }
  36346. else {
  36347. type = "DIRLIGHT" + lightIndex;
  36348. }
  36349. defines[type] = true;
  36350. // Specular
  36351. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36352. specularEnabled = true;
  36353. }
  36354. // Shadows
  36355. defines["SHADOW" + lightIndex] = false;
  36356. defines["SHADOWPCF" + lightIndex] = false;
  36357. defines["SHADOWESM" + lightIndex] = false;
  36358. defines["SHADOWCUBE" + lightIndex] = false;
  36359. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36360. var shadowGenerator = light.getShadowGenerator();
  36361. if (shadowGenerator) {
  36362. shadowEnabled = true;
  36363. shadowGenerator.prepareDefines(defines, lightIndex);
  36364. }
  36365. }
  36366. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36367. lightmapMode = true;
  36368. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36369. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36370. }
  36371. else {
  36372. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36373. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36374. }
  36375. lightIndex++;
  36376. if (lightIndex === maxSimultaneousLights)
  36377. break;
  36378. }
  36379. }
  36380. defines["SPECULARTERM"] = specularEnabled;
  36381. defines["SHADOWS"] = shadowEnabled;
  36382. // Resetting all other lights if any
  36383. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36384. if (defines["LIGHT" + index] !== undefined) {
  36385. defines["LIGHT" + index] = false;
  36386. defines["HEMILIGHT" + lightIndex] = false;
  36387. defines["POINTLIGHT" + lightIndex] = false;
  36388. defines["DIRLIGHT" + lightIndex] = false;
  36389. defines["SPOTLIGHT" + lightIndex] = false;
  36390. defines["SHADOW" + lightIndex] = false;
  36391. }
  36392. }
  36393. var caps = scene.getEngine().getCaps();
  36394. if (defines["SHADOWFLOAT"] === undefined) {
  36395. needRebuild = true;
  36396. }
  36397. defines["SHADOWFLOAT"] = shadowEnabled &&
  36398. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36399. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36400. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36401. if (needRebuild) {
  36402. defines.rebuild();
  36403. }
  36404. return needNormals;
  36405. };
  36406. /**
  36407. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  36408. * that won t be acctive due to defines being turned off.
  36409. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  36410. * @param samplersList The samplers list
  36411. * @param defines The defines helping in the list generation
  36412. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  36413. */
  36414. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36415. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36416. var uniformsList;
  36417. var uniformBuffersList = null;
  36418. if (uniformsListOrOptions.uniformsNames) {
  36419. var options = uniformsListOrOptions;
  36420. uniformsList = options.uniformsNames;
  36421. uniformBuffersList = options.uniformBuffersNames;
  36422. samplersList = options.samplers;
  36423. defines = options.defines;
  36424. maxSimultaneousLights = options.maxSimultaneousLights;
  36425. }
  36426. else {
  36427. uniformsList = uniformsListOrOptions;
  36428. if (!samplersList) {
  36429. samplersList = [];
  36430. }
  36431. }
  36432. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36433. if (!defines["LIGHT" + lightIndex]) {
  36434. break;
  36435. }
  36436. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36437. if (uniformBuffersList) {
  36438. uniformBuffersList.push("Light" + lightIndex);
  36439. }
  36440. samplersList.push("shadowSampler" + lightIndex);
  36441. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  36442. samplersList.push("projectionLightSampler" + lightIndex);
  36443. uniformsList.push("textureProjectionMatrix" + lightIndex);
  36444. }
  36445. }
  36446. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36447. uniformsList.push("morphTargetInfluences");
  36448. }
  36449. };
  36450. /**
  36451. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  36452. * @param defines The defines to update while falling back
  36453. * @param fallbacks The authorized effect fallbacks
  36454. * @param maxSimultaneousLights The maximum number of lights allowed
  36455. * @param rank the current rank of the Effect
  36456. * @returns The newly affected rank
  36457. */
  36458. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36459. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36460. if (rank === void 0) { rank = 0; }
  36461. var lightFallbackRank = 0;
  36462. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36463. if (!defines["LIGHT" + lightIndex]) {
  36464. break;
  36465. }
  36466. if (lightIndex > 0) {
  36467. lightFallbackRank = rank + lightIndex;
  36468. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36469. }
  36470. if (!defines["SHADOWS"]) {
  36471. if (defines["SHADOW" + lightIndex]) {
  36472. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36473. }
  36474. if (defines["SHADOWPCF" + lightIndex]) {
  36475. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36476. }
  36477. if (defines["SHADOWESM" + lightIndex]) {
  36478. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36479. }
  36480. }
  36481. }
  36482. return lightFallbackRank++;
  36483. };
  36484. /**
  36485. * Prepares the list of attributes required for morph targets according to the effect defines.
  36486. * @param attribs The current list of supported attribs
  36487. * @param mesh The mesh to prepare the morph targets attributes for
  36488. * @param defines The current Defines of the effect
  36489. */
  36490. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36491. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36492. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36493. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36494. var manager = mesh.morphTargetManager;
  36495. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36496. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36497. for (var index = 0; index < influencers; index++) {
  36498. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36499. if (normal) {
  36500. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36501. }
  36502. if (tangent) {
  36503. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36504. }
  36505. if (attribs.length > maxAttributesCount) {
  36506. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36507. }
  36508. }
  36509. }
  36510. };
  36511. /**
  36512. * Prepares the list of attributes required for bones according to the effect defines.
  36513. * @param attribs The current list of supported attribs
  36514. * @param mesh The mesh to prepare the bones attributes for
  36515. * @param defines The current Defines of the effect
  36516. * @param fallbacks The current efffect fallback strategy
  36517. */
  36518. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36519. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36520. fallbacks.addCPUSkinningFallback(0, mesh);
  36521. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36522. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36523. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36524. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36525. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36526. }
  36527. }
  36528. };
  36529. /**
  36530. * Prepares the list of attributes required for instances according to the effect defines.
  36531. * @param attribs The current list of supported attribs
  36532. * @param defines The current Defines of the effect
  36533. */
  36534. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36535. if (defines["INSTANCES"]) {
  36536. attribs.push("world0");
  36537. attribs.push("world1");
  36538. attribs.push("world2");
  36539. attribs.push("world3");
  36540. }
  36541. };
  36542. /**
  36543. * Binds the light shadow information to the effect for the given mesh.
  36544. * @param light The light containing the generator
  36545. * @param scene The scene the lights belongs to
  36546. * @param mesh The mesh we are binding the information to render
  36547. * @param lightIndex The light index in the effect used to render the mesh
  36548. * @param effect The effect we are binding the data to
  36549. */
  36550. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36551. if (light.shadowEnabled && mesh.receiveShadows) {
  36552. var shadowGenerator = light.getShadowGenerator();
  36553. if (shadowGenerator) {
  36554. shadowGenerator.bindShadowLight(lightIndex, effect);
  36555. }
  36556. }
  36557. };
  36558. /**
  36559. * Binds the light information to the effect.
  36560. * @param light The light containing the generator
  36561. * @param effect The effect we are binding the data to
  36562. * @param lightIndex The light index in the effect used to render
  36563. */
  36564. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36565. light.transferToEffect(effect, lightIndex + "");
  36566. };
  36567. /**
  36568. * Binds the lights information from the scene to the effect for the given mesh.
  36569. * @param scene The scene the lights belongs to
  36570. * @param mesh The mesh we are binding the information to render
  36571. * @param effect The effect we are binding the data to
  36572. * @param defines The generated defines for the effect
  36573. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  36574. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  36575. */
  36576. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36577. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36578. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36579. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36580. for (var i = 0; i < len; i++) {
  36581. var light = mesh._lightSources[i];
  36582. var iAsString = i.toString();
  36583. var scaledIntensity = light.getScaledIntensity();
  36584. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36585. MaterialHelper.BindLightProperties(light, effect, i);
  36586. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36587. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36588. if (defines["SPECULARTERM"]) {
  36589. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36590. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36591. }
  36592. // Shadows
  36593. if (scene.shadowsEnabled) {
  36594. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36595. }
  36596. light._uniformBuffer.update();
  36597. }
  36598. };
  36599. /**
  36600. * Binds the fog information from the scene to the effect for the given mesh.
  36601. * @param scene The scene the lights belongs to
  36602. * @param mesh The mesh we are binding the information to render
  36603. * @param effect The effect we are binding the data to
  36604. */
  36605. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36606. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36607. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36608. effect.setColor3("vFogColor", scene.fogColor);
  36609. }
  36610. };
  36611. /**
  36612. * Binds the bones information from the mesh to the effect.
  36613. * @param mesh The mesh we are binding the information to render
  36614. * @param effect The effect we are binding the data to
  36615. */
  36616. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36617. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36618. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36619. if (matrices && effect) {
  36620. effect.setMatrices("mBones", matrices);
  36621. }
  36622. }
  36623. };
  36624. /**
  36625. * Binds the morph targets information from the mesh to the effect.
  36626. * @param abstractMesh The mesh we are binding the information to render
  36627. * @param effect The effect we are binding the data to
  36628. */
  36629. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36630. var manager = abstractMesh.morphTargetManager;
  36631. if (!abstractMesh || !manager) {
  36632. return;
  36633. }
  36634. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36635. };
  36636. /**
  36637. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  36638. * @param defines The generated defines used in the effect
  36639. * @param effect The effect we are binding the data to
  36640. * @param scene The scene we are willing to render with logarithmic scale for
  36641. */
  36642. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36643. if (defines["LOGARITHMICDEPTH"]) {
  36644. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36645. }
  36646. };
  36647. /**
  36648. * Binds the clip plane information from the scene to the effect.
  36649. * @param scene The scene the clip plane information are extracted from
  36650. * @param effect The effect we are binding the data to
  36651. */
  36652. MaterialHelper.BindClipPlane = function (effect, scene) {
  36653. if (scene.clipPlane) {
  36654. var clipPlane = scene.clipPlane;
  36655. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36656. }
  36657. };
  36658. return MaterialHelper;
  36659. }());
  36660. BABYLON.MaterialHelper = MaterialHelper;
  36661. })(BABYLON || (BABYLON = {}));
  36662. //# sourceMappingURL=babylon.materialHelper.js.map
  36663. var BABYLON;
  36664. (function (BABYLON) {
  36665. var PushMaterial = /** @class */ (function (_super) {
  36666. __extends(PushMaterial, _super);
  36667. function PushMaterial(name, scene) {
  36668. var _this = _super.call(this, name, scene) || this;
  36669. _this.storeEffectOnSubMeshes = true;
  36670. return _this;
  36671. }
  36672. PushMaterial.prototype.getEffect = function () {
  36673. return this._activeEffect;
  36674. };
  36675. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36676. if (!mesh) {
  36677. return false;
  36678. }
  36679. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36680. return true;
  36681. }
  36682. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36683. };
  36684. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36685. this._activeEffect.setMatrix("world", world);
  36686. };
  36687. PushMaterial.prototype.bind = function (world, mesh) {
  36688. if (!mesh) {
  36689. return;
  36690. }
  36691. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36692. };
  36693. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36694. if (effect === void 0) { effect = null; }
  36695. _super.prototype._afterBind.call(this, mesh);
  36696. this.getScene()._cachedEffect = effect;
  36697. };
  36698. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36699. if (visibility === void 0) { visibility = 1; }
  36700. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36701. };
  36702. return PushMaterial;
  36703. }(BABYLON.Material));
  36704. BABYLON.PushMaterial = PushMaterial;
  36705. })(BABYLON || (BABYLON = {}));
  36706. //# sourceMappingURL=babylon.pushMaterial.js.map
  36707. var BABYLON;
  36708. (function (BABYLON) {
  36709. var StandardMaterialDefines = /** @class */ (function (_super) {
  36710. __extends(StandardMaterialDefines, _super);
  36711. function StandardMaterialDefines() {
  36712. var _this = _super.call(this) || this;
  36713. _this.MAINUV1 = false;
  36714. _this.MAINUV2 = false;
  36715. _this.DIFFUSE = false;
  36716. _this.DIFFUSEDIRECTUV = 0;
  36717. _this.AMBIENT = false;
  36718. _this.AMBIENTDIRECTUV = 0;
  36719. _this.OPACITY = false;
  36720. _this.OPACITYDIRECTUV = 0;
  36721. _this.OPACITYRGB = false;
  36722. _this.REFLECTION = false;
  36723. _this.EMISSIVE = false;
  36724. _this.EMISSIVEDIRECTUV = 0;
  36725. _this.SPECULAR = false;
  36726. _this.SPECULARDIRECTUV = 0;
  36727. _this.BUMP = false;
  36728. _this.BUMPDIRECTUV = 0;
  36729. _this.PARALLAX = false;
  36730. _this.PARALLAXOCCLUSION = false;
  36731. _this.SPECULAROVERALPHA = false;
  36732. _this.CLIPPLANE = false;
  36733. _this.ALPHATEST = false;
  36734. _this.DEPTHPREPASS = false;
  36735. _this.ALPHAFROMDIFFUSE = false;
  36736. _this.POINTSIZE = false;
  36737. _this.FOG = false;
  36738. _this.SPECULARTERM = false;
  36739. _this.DIFFUSEFRESNEL = false;
  36740. _this.OPACITYFRESNEL = false;
  36741. _this.REFLECTIONFRESNEL = false;
  36742. _this.REFRACTIONFRESNEL = false;
  36743. _this.EMISSIVEFRESNEL = false;
  36744. _this.FRESNEL = false;
  36745. _this.NORMAL = false;
  36746. _this.UV1 = false;
  36747. _this.UV2 = false;
  36748. _this.VERTEXCOLOR = false;
  36749. _this.VERTEXALPHA = false;
  36750. _this.NUM_BONE_INFLUENCERS = 0;
  36751. _this.BonesPerMesh = 0;
  36752. _this.INSTANCES = false;
  36753. _this.GLOSSINESS = false;
  36754. _this.ROUGHNESS = false;
  36755. _this.EMISSIVEASILLUMINATION = false;
  36756. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36757. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36758. _this.LIGHTMAP = false;
  36759. _this.LIGHTMAPDIRECTUV = 0;
  36760. _this.USELIGHTMAPASSHADOWMAP = false;
  36761. _this.REFLECTIONMAP_3D = false;
  36762. _this.REFLECTIONMAP_SPHERICAL = false;
  36763. _this.REFLECTIONMAP_PLANAR = false;
  36764. _this.REFLECTIONMAP_CUBIC = false;
  36765. _this.REFLECTIONMAP_PROJECTION = false;
  36766. _this.REFLECTIONMAP_SKYBOX = false;
  36767. _this.REFLECTIONMAP_EXPLICIT = false;
  36768. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36769. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36770. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36771. _this.INVERTCUBICMAP = false;
  36772. _this.LOGARITHMICDEPTH = false;
  36773. _this.REFRACTION = false;
  36774. _this.REFRACTIONMAP_3D = false;
  36775. _this.REFLECTIONOVERALPHA = false;
  36776. _this.TWOSIDEDLIGHTING = false;
  36777. _this.SHADOWFLOAT = false;
  36778. _this.MORPHTARGETS = false;
  36779. _this.MORPHTARGETS_NORMAL = false;
  36780. _this.MORPHTARGETS_TANGENT = false;
  36781. _this.NUM_MORPH_INFLUENCERS = 0;
  36782. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36783. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36784. _this.IMAGEPROCESSING = false;
  36785. _this.VIGNETTE = false;
  36786. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36787. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36788. _this.TONEMAPPING = false;
  36789. _this.CONTRAST = false;
  36790. _this.COLORCURVES = false;
  36791. _this.COLORGRADING = false;
  36792. _this.COLORGRADING3D = false;
  36793. _this.SAMPLER3DGREENDEPTH = false;
  36794. _this.SAMPLER3DBGRMAP = false;
  36795. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36796. _this.EXPOSURE = false;
  36797. _this.rebuild();
  36798. return _this;
  36799. }
  36800. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36801. var modes = [
  36802. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36803. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36804. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36805. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36806. ];
  36807. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36808. var mode = modes_1[_i];
  36809. this[mode] = (mode === modeToEnable);
  36810. }
  36811. };
  36812. return StandardMaterialDefines;
  36813. }(BABYLON.MaterialDefines));
  36814. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36815. var StandardMaterial = /** @class */ (function (_super) {
  36816. __extends(StandardMaterial, _super);
  36817. function StandardMaterial(name, scene) {
  36818. var _this = _super.call(this, name, scene) || this;
  36819. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36820. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36821. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36822. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36823. _this.specularPower = 64;
  36824. _this._useAlphaFromDiffuseTexture = false;
  36825. _this._useEmissiveAsIllumination = false;
  36826. _this._linkEmissiveWithDiffuse = false;
  36827. _this._useSpecularOverAlpha = false;
  36828. _this._useReflectionOverAlpha = false;
  36829. _this._disableLighting = false;
  36830. _this._useParallax = false;
  36831. _this._useParallaxOcclusion = false;
  36832. _this.parallaxScaleBias = 0.05;
  36833. _this._roughness = 0;
  36834. _this.indexOfRefraction = 0.98;
  36835. _this.invertRefractionY = true;
  36836. _this._useLightmapAsShadowmap = false;
  36837. _this._useReflectionFresnelFromSpecular = false;
  36838. _this._useGlossinessFromSpecularMapAlpha = false;
  36839. _this._maxSimultaneousLights = 4;
  36840. /**
  36841. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36842. */
  36843. _this._invertNormalMapX = false;
  36844. /**
  36845. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36846. */
  36847. _this._invertNormalMapY = false;
  36848. /**
  36849. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36850. */
  36851. _this._twoSidedLighting = false;
  36852. _this._renderTargets = new BABYLON.SmartArray(16);
  36853. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36854. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36855. // Setup the default processing configuration to the scene.
  36856. _this._attachImageProcessingConfiguration(null);
  36857. _this.getRenderTargetTextures = function () {
  36858. _this._renderTargets.reset();
  36859. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36860. _this._renderTargets.push(_this._reflectionTexture);
  36861. }
  36862. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36863. _this._renderTargets.push(_this._refractionTexture);
  36864. }
  36865. return _this._renderTargets;
  36866. };
  36867. return _this;
  36868. }
  36869. ;
  36870. ;
  36871. ;
  36872. ;
  36873. ;
  36874. ;
  36875. ;
  36876. ;
  36877. ;
  36878. ;
  36879. ;
  36880. ;
  36881. ;
  36882. ;
  36883. ;
  36884. ;
  36885. ;
  36886. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36887. /**
  36888. * Gets the image processing configuration used either in this material.
  36889. */
  36890. get: function () {
  36891. return this._imageProcessingConfiguration;
  36892. },
  36893. /**
  36894. * Sets the Default image processing configuration used either in the this material.
  36895. *
  36896. * If sets to null, the scene one is in use.
  36897. */
  36898. set: function (value) {
  36899. this._attachImageProcessingConfiguration(value);
  36900. // Ensure the effect will be rebuilt.
  36901. this._markAllSubMeshesAsTexturesDirty();
  36902. },
  36903. enumerable: true,
  36904. configurable: true
  36905. });
  36906. /**
  36907. * Attaches a new image processing configuration to the Standard Material.
  36908. * @param configuration
  36909. */
  36910. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36911. var _this = this;
  36912. if (configuration === this._imageProcessingConfiguration) {
  36913. return;
  36914. }
  36915. // Detaches observer.
  36916. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36917. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36918. }
  36919. // Pick the scene configuration if needed.
  36920. if (!configuration) {
  36921. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36922. }
  36923. else {
  36924. this._imageProcessingConfiguration = configuration;
  36925. }
  36926. // Attaches observer.
  36927. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36928. _this._markAllSubMeshesAsImageProcessingDirty();
  36929. });
  36930. };
  36931. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36932. /**
  36933. * Gets wether the color curves effect is enabled.
  36934. */
  36935. get: function () {
  36936. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36937. },
  36938. /**
  36939. * Sets wether the color curves effect is enabled.
  36940. */
  36941. set: function (value) {
  36942. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36943. },
  36944. enumerable: true,
  36945. configurable: true
  36946. });
  36947. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36948. /**
  36949. * Gets wether the color grading effect is enabled.
  36950. */
  36951. get: function () {
  36952. return this.imageProcessingConfiguration.colorGradingEnabled;
  36953. },
  36954. /**
  36955. * Gets wether the color grading effect is enabled.
  36956. */
  36957. set: function (value) {
  36958. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36959. },
  36960. enumerable: true,
  36961. configurable: true
  36962. });
  36963. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36964. /**
  36965. * Gets wether tonemapping is enabled or not.
  36966. */
  36967. get: function () {
  36968. return this._imageProcessingConfiguration.toneMappingEnabled;
  36969. },
  36970. /**
  36971. * Sets wether tonemapping is enabled or not
  36972. */
  36973. set: function (value) {
  36974. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36975. },
  36976. enumerable: true,
  36977. configurable: true
  36978. });
  36979. ;
  36980. ;
  36981. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36982. /**
  36983. * The camera exposure used on this material.
  36984. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36985. * This corresponds to a photographic exposure.
  36986. */
  36987. get: function () {
  36988. return this._imageProcessingConfiguration.exposure;
  36989. },
  36990. /**
  36991. * The camera exposure used on this material.
  36992. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36993. * This corresponds to a photographic exposure.
  36994. */
  36995. set: function (value) {
  36996. this._imageProcessingConfiguration.exposure = value;
  36997. },
  36998. enumerable: true,
  36999. configurable: true
  37000. });
  37001. ;
  37002. ;
  37003. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  37004. /**
  37005. * Gets The camera contrast used on this material.
  37006. */
  37007. get: function () {
  37008. return this._imageProcessingConfiguration.contrast;
  37009. },
  37010. /**
  37011. * Sets The camera contrast used on this material.
  37012. */
  37013. set: function (value) {
  37014. this._imageProcessingConfiguration.contrast = value;
  37015. },
  37016. enumerable: true,
  37017. configurable: true
  37018. });
  37019. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  37020. /**
  37021. * Gets the Color Grading 2D Lookup Texture.
  37022. */
  37023. get: function () {
  37024. return this._imageProcessingConfiguration.colorGradingTexture;
  37025. },
  37026. /**
  37027. * Sets the Color Grading 2D Lookup Texture.
  37028. */
  37029. set: function (value) {
  37030. this._imageProcessingConfiguration.colorGradingTexture = value;
  37031. },
  37032. enumerable: true,
  37033. configurable: true
  37034. });
  37035. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  37036. /**
  37037. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37038. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37039. * 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;
  37040. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37041. */
  37042. get: function () {
  37043. return this._imageProcessingConfiguration.colorCurves;
  37044. },
  37045. /**
  37046. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37047. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37048. * 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;
  37049. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37050. */
  37051. set: function (value) {
  37052. this._imageProcessingConfiguration.colorCurves = value;
  37053. },
  37054. enumerable: true,
  37055. configurable: true
  37056. });
  37057. StandardMaterial.prototype.getClassName = function () {
  37058. return "StandardMaterial";
  37059. };
  37060. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  37061. get: function () {
  37062. return this._useLogarithmicDepth;
  37063. },
  37064. set: function (value) {
  37065. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37066. this._markAllSubMeshesAsMiscDirty();
  37067. },
  37068. enumerable: true,
  37069. configurable: true
  37070. });
  37071. StandardMaterial.prototype.needAlphaBlending = function () {
  37072. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  37073. };
  37074. StandardMaterial.prototype.needAlphaTesting = function () {
  37075. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  37076. };
  37077. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  37078. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  37079. };
  37080. StandardMaterial.prototype.getAlphaTestTexture = function () {
  37081. return this._diffuseTexture;
  37082. };
  37083. /**
  37084. * Child classes can use it to update shaders
  37085. */
  37086. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37087. if (useInstances === void 0) { useInstances = false; }
  37088. if (subMesh.effect && this.isFrozen) {
  37089. if (this._wasPreviouslyReady && subMesh.effect) {
  37090. return true;
  37091. }
  37092. }
  37093. if (!subMesh._materialDefines) {
  37094. subMesh._materialDefines = new StandardMaterialDefines();
  37095. }
  37096. var scene = this.getScene();
  37097. var defines = subMesh._materialDefines;
  37098. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37099. if (defines._renderId === scene.getRenderId()) {
  37100. return true;
  37101. }
  37102. }
  37103. var engine = scene.getEngine();
  37104. // Lights
  37105. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37106. // Textures
  37107. if (defines._areTexturesDirty) {
  37108. defines._needUVs = false;
  37109. defines.MAINUV1 = false;
  37110. defines.MAINUV2 = false;
  37111. if (scene.texturesEnabled) {
  37112. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37113. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  37114. return false;
  37115. }
  37116. else {
  37117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  37118. }
  37119. }
  37120. else {
  37121. defines.DIFFUSE = false;
  37122. }
  37123. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37124. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37125. return false;
  37126. }
  37127. else {
  37128. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37129. }
  37130. }
  37131. else {
  37132. defines.AMBIENT = false;
  37133. }
  37134. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37135. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37136. return false;
  37137. }
  37138. else {
  37139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37140. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37141. }
  37142. }
  37143. else {
  37144. defines.OPACITY = false;
  37145. }
  37146. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37147. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  37148. return false;
  37149. }
  37150. else {
  37151. defines._needNormals = true;
  37152. defines.REFLECTION = true;
  37153. defines.ROUGHNESS = (this._roughness > 0);
  37154. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  37155. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  37156. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  37157. switch (this._reflectionTexture.coordinatesMode) {
  37158. case BABYLON.Texture.CUBIC_MODE:
  37159. case BABYLON.Texture.INVCUBIC_MODE:
  37160. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  37161. break;
  37162. case BABYLON.Texture.EXPLICIT_MODE:
  37163. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  37164. break;
  37165. case BABYLON.Texture.PLANAR_MODE:
  37166. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  37167. break;
  37168. case BABYLON.Texture.PROJECTION_MODE:
  37169. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  37170. break;
  37171. case BABYLON.Texture.SKYBOX_MODE:
  37172. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  37173. break;
  37174. case BABYLON.Texture.SPHERICAL_MODE:
  37175. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  37176. break;
  37177. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37178. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  37179. break;
  37180. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37181. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  37182. break;
  37183. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37184. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  37185. break;
  37186. }
  37187. }
  37188. }
  37189. else {
  37190. defines.REFLECTION = false;
  37191. }
  37192. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37193. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37194. return false;
  37195. }
  37196. else {
  37197. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37198. }
  37199. }
  37200. else {
  37201. defines.EMISSIVE = false;
  37202. }
  37203. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37204. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37205. return false;
  37206. }
  37207. else {
  37208. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37209. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37210. }
  37211. }
  37212. else {
  37213. defines.LIGHTMAP = false;
  37214. }
  37215. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37216. if (!this._specularTexture.isReadyOrNotBlocking()) {
  37217. return false;
  37218. }
  37219. else {
  37220. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  37221. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  37222. }
  37223. }
  37224. else {
  37225. defines.SPECULAR = false;
  37226. }
  37227. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  37228. // Bump texure can not be not blocking.
  37229. if (!this._bumpTexture.isReady()) {
  37230. return false;
  37231. }
  37232. else {
  37233. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37234. defines.PARALLAX = this._useParallax;
  37235. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  37236. }
  37237. }
  37238. else {
  37239. defines.BUMP = false;
  37240. }
  37241. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37242. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  37243. return false;
  37244. }
  37245. else {
  37246. defines._needUVs = true;
  37247. defines.REFRACTION = true;
  37248. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  37249. }
  37250. }
  37251. else {
  37252. defines.REFRACTION = false;
  37253. }
  37254. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  37255. }
  37256. else {
  37257. defines.DIFFUSE = false;
  37258. defines.AMBIENT = false;
  37259. defines.OPACITY = false;
  37260. defines.REFLECTION = false;
  37261. defines.EMISSIVE = false;
  37262. defines.LIGHTMAP = false;
  37263. defines.BUMP = false;
  37264. defines.REFRACTION = false;
  37265. }
  37266. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37267. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37268. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37269. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37270. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37271. }
  37272. if (defines._areImageProcessingDirty) {
  37273. if (!this._imageProcessingConfiguration.isReady()) {
  37274. return false;
  37275. }
  37276. this._imageProcessingConfiguration.prepareDefines(defines);
  37277. }
  37278. if (defines._areFresnelDirty) {
  37279. if (StandardMaterial.FresnelEnabled) {
  37280. // Fresnel
  37281. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37282. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37283. this._reflectionFresnelParameters) {
  37284. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37285. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37286. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37287. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37288. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37289. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37290. defines._needNormals = true;
  37291. defines.FRESNEL = true;
  37292. }
  37293. }
  37294. else {
  37295. defines.FRESNEL = false;
  37296. }
  37297. }
  37298. // Misc.
  37299. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37300. // Attribs
  37301. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37302. // Values that need to be evaluated on every frame
  37303. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37304. // Get correct effect
  37305. if (defines.isDirty) {
  37306. defines.markAsProcessed();
  37307. scene.resetCachedMaterial();
  37308. // Fallbacks
  37309. var fallbacks = new BABYLON.EffectFallbacks();
  37310. if (defines.REFLECTION) {
  37311. fallbacks.addFallback(0, "REFLECTION");
  37312. }
  37313. if (defines.SPECULAR) {
  37314. fallbacks.addFallback(0, "SPECULAR");
  37315. }
  37316. if (defines.BUMP) {
  37317. fallbacks.addFallback(0, "BUMP");
  37318. }
  37319. if (defines.PARALLAX) {
  37320. fallbacks.addFallback(1, "PARALLAX");
  37321. }
  37322. if (defines.PARALLAXOCCLUSION) {
  37323. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37324. }
  37325. if (defines.SPECULAROVERALPHA) {
  37326. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37327. }
  37328. if (defines.FOG) {
  37329. fallbacks.addFallback(1, "FOG");
  37330. }
  37331. if (defines.POINTSIZE) {
  37332. fallbacks.addFallback(0, "POINTSIZE");
  37333. }
  37334. if (defines.LOGARITHMICDEPTH) {
  37335. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37336. }
  37337. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37338. if (defines.SPECULARTERM) {
  37339. fallbacks.addFallback(0, "SPECULARTERM");
  37340. }
  37341. if (defines.DIFFUSEFRESNEL) {
  37342. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37343. }
  37344. if (defines.OPACITYFRESNEL) {
  37345. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37346. }
  37347. if (defines.REFLECTIONFRESNEL) {
  37348. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37349. }
  37350. if (defines.EMISSIVEFRESNEL) {
  37351. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37352. }
  37353. if (defines.FRESNEL) {
  37354. fallbacks.addFallback(4, "FRESNEL");
  37355. }
  37356. //Attributes
  37357. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37358. if (defines.NORMAL) {
  37359. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37360. }
  37361. if (defines.UV1) {
  37362. attribs.push(BABYLON.VertexBuffer.UVKind);
  37363. }
  37364. if (defines.UV2) {
  37365. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37366. }
  37367. if (defines.VERTEXCOLOR) {
  37368. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37369. }
  37370. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37371. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37372. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37373. var shaderName = "default";
  37374. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37375. "vFogInfos", "vFogColor", "pointSize",
  37376. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37377. "mBones",
  37378. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37379. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37380. "logarithmicDepthConstant", "vTangentSpaceParams"
  37381. ];
  37382. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37383. var uniformBuffers = ["Material", "Scene"];
  37384. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37385. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37386. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37387. uniformsNames: uniforms,
  37388. uniformBuffersNames: uniformBuffers,
  37389. samplers: samplers,
  37390. defines: defines,
  37391. maxSimultaneousLights: this._maxSimultaneousLights
  37392. });
  37393. if (this.customShaderNameResolve) {
  37394. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37395. }
  37396. var join = defines.toString();
  37397. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37398. attributes: attribs,
  37399. uniformsNames: uniforms,
  37400. uniformBuffersNames: uniformBuffers,
  37401. samplers: samplers,
  37402. defines: join,
  37403. fallbacks: fallbacks,
  37404. onCompiled: this.onCompiled,
  37405. onError: this.onError,
  37406. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37407. }, engine), defines);
  37408. this.buildUniformLayout();
  37409. }
  37410. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37411. return false;
  37412. }
  37413. defines._renderId = scene.getRenderId();
  37414. this._wasPreviouslyReady = true;
  37415. return true;
  37416. };
  37417. StandardMaterial.prototype.buildUniformLayout = function () {
  37418. // Order is important !
  37419. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37420. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37421. this._uniformBuffer.addUniform("opacityParts", 4);
  37422. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37423. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37424. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37425. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37426. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37427. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37428. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37429. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37430. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37431. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37432. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37433. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37434. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37435. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37436. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37437. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37438. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37439. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37440. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37441. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37442. this._uniformBuffer.addUniform("specularMatrix", 16);
  37443. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37444. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37445. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37446. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37447. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37448. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37449. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37450. this._uniformBuffer.addUniform("pointSize", 1);
  37451. this._uniformBuffer.create();
  37452. };
  37453. StandardMaterial.prototype.unbind = function () {
  37454. if (this._activeEffect) {
  37455. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37456. this._activeEffect.setTexture("reflection2DSampler", null);
  37457. }
  37458. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37459. this._activeEffect.setTexture("refraction2DSampler", null);
  37460. }
  37461. }
  37462. _super.prototype.unbind.call(this);
  37463. };
  37464. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37465. var scene = this.getScene();
  37466. var defines = subMesh._materialDefines;
  37467. if (!defines) {
  37468. return;
  37469. }
  37470. var effect = subMesh.effect;
  37471. if (!effect) {
  37472. return;
  37473. }
  37474. this._activeEffect = effect;
  37475. // Matrices
  37476. this.bindOnlyWorldMatrix(world);
  37477. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37478. // Bones
  37479. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37480. if (mustRebind) {
  37481. this._uniformBuffer.bindToEffect(effect, "Material");
  37482. this.bindViewProjection(effect);
  37483. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37484. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37485. // Fresnel
  37486. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37487. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37488. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37489. }
  37490. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37491. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37492. }
  37493. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37494. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37495. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37496. }
  37497. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37498. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37499. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37500. }
  37501. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37502. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37503. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37504. }
  37505. }
  37506. // Textures
  37507. if (scene.texturesEnabled) {
  37508. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37509. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37510. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37511. }
  37512. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37513. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37514. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37515. }
  37516. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37517. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37518. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37519. }
  37520. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37521. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37522. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37523. }
  37524. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37525. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37526. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37527. }
  37528. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37529. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37530. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37531. }
  37532. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37533. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37534. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37535. }
  37536. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37537. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37538. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37539. if (scene._mirroredCameraPosition) {
  37540. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37541. }
  37542. else {
  37543. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37544. }
  37545. }
  37546. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37547. var depth = 1.0;
  37548. if (!this._refractionTexture.isCube) {
  37549. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37550. if (this._refractionTexture.depth) {
  37551. depth = this._refractionTexture.depth;
  37552. }
  37553. }
  37554. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37555. }
  37556. }
  37557. // Point size
  37558. if (this.pointsCloud) {
  37559. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37560. }
  37561. if (defines.SPECULARTERM) {
  37562. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37563. }
  37564. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37565. // Diffuse
  37566. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37567. }
  37568. // Textures
  37569. if (scene.texturesEnabled) {
  37570. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37571. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37572. }
  37573. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37574. effect.setTexture("ambientSampler", this._ambientTexture);
  37575. }
  37576. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37577. effect.setTexture("opacitySampler", this._opacityTexture);
  37578. }
  37579. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37580. if (this._reflectionTexture.isCube) {
  37581. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37582. }
  37583. else {
  37584. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37585. }
  37586. }
  37587. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37588. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37589. }
  37590. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37591. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37592. }
  37593. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37594. effect.setTexture("specularSampler", this._specularTexture);
  37595. }
  37596. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37597. effect.setTexture("bumpSampler", this._bumpTexture);
  37598. }
  37599. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37600. var depth = 1.0;
  37601. if (this._refractionTexture.isCube) {
  37602. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37603. }
  37604. else {
  37605. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37606. }
  37607. }
  37608. }
  37609. // Clip plane
  37610. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37611. // Colors
  37612. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37613. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37614. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37615. }
  37616. if (mustRebind || !this.isFrozen) {
  37617. // Lights
  37618. if (scene.lightsEnabled && !this._disableLighting) {
  37619. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37620. }
  37621. // View
  37622. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37623. this.bindView(effect);
  37624. }
  37625. // Fog
  37626. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37627. // Morph targets
  37628. if (defines.NUM_MORPH_INFLUENCERS) {
  37629. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37630. }
  37631. // Log. depth
  37632. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37633. // image processing
  37634. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37635. this._imageProcessingConfiguration.bind(this._activeEffect);
  37636. }
  37637. }
  37638. this._uniformBuffer.update();
  37639. this._afterBind(mesh, this._activeEffect);
  37640. };
  37641. StandardMaterial.prototype.getAnimatables = function () {
  37642. var results = [];
  37643. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37644. results.push(this._diffuseTexture);
  37645. }
  37646. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37647. results.push(this._ambientTexture);
  37648. }
  37649. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37650. results.push(this._opacityTexture);
  37651. }
  37652. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37653. results.push(this._reflectionTexture);
  37654. }
  37655. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37656. results.push(this._emissiveTexture);
  37657. }
  37658. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37659. results.push(this._specularTexture);
  37660. }
  37661. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37662. results.push(this._bumpTexture);
  37663. }
  37664. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37665. results.push(this._lightmapTexture);
  37666. }
  37667. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37668. results.push(this._refractionTexture);
  37669. }
  37670. return results;
  37671. };
  37672. StandardMaterial.prototype.getActiveTextures = function () {
  37673. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37674. if (this._diffuseTexture) {
  37675. activeTextures.push(this._diffuseTexture);
  37676. }
  37677. if (this._ambientTexture) {
  37678. activeTextures.push(this._ambientTexture);
  37679. }
  37680. if (this._opacityTexture) {
  37681. activeTextures.push(this._opacityTexture);
  37682. }
  37683. if (this._reflectionTexture) {
  37684. activeTextures.push(this._reflectionTexture);
  37685. }
  37686. if (this._emissiveTexture) {
  37687. activeTextures.push(this._emissiveTexture);
  37688. }
  37689. if (this._specularTexture) {
  37690. activeTextures.push(this._specularTexture);
  37691. }
  37692. if (this._bumpTexture) {
  37693. activeTextures.push(this._bumpTexture);
  37694. }
  37695. if (this._lightmapTexture) {
  37696. activeTextures.push(this._lightmapTexture);
  37697. }
  37698. if (this._refractionTexture) {
  37699. activeTextures.push(this._refractionTexture);
  37700. }
  37701. return activeTextures;
  37702. };
  37703. StandardMaterial.prototype.hasTexture = function (texture) {
  37704. if (_super.prototype.hasTexture.call(this, texture)) {
  37705. return true;
  37706. }
  37707. if (this._diffuseTexture === texture) {
  37708. return true;
  37709. }
  37710. if (this._ambientTexture === texture) {
  37711. return true;
  37712. }
  37713. if (this._opacityTexture === texture) {
  37714. return true;
  37715. }
  37716. if (this._reflectionTexture === texture) {
  37717. return true;
  37718. }
  37719. if (this._emissiveTexture === texture) {
  37720. return true;
  37721. }
  37722. if (this._specularTexture === texture) {
  37723. return true;
  37724. }
  37725. if (this._bumpTexture === texture) {
  37726. return true;
  37727. }
  37728. if (this._lightmapTexture === texture) {
  37729. return true;
  37730. }
  37731. if (this._refractionTexture === texture) {
  37732. return true;
  37733. }
  37734. return false;
  37735. };
  37736. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37737. if (forceDisposeTextures) {
  37738. if (this._diffuseTexture) {
  37739. this._diffuseTexture.dispose();
  37740. }
  37741. if (this._ambientTexture) {
  37742. this._ambientTexture.dispose();
  37743. }
  37744. if (this._opacityTexture) {
  37745. this._opacityTexture.dispose();
  37746. }
  37747. if (this._reflectionTexture) {
  37748. this._reflectionTexture.dispose();
  37749. }
  37750. if (this._emissiveTexture) {
  37751. this._emissiveTexture.dispose();
  37752. }
  37753. if (this._specularTexture) {
  37754. this._specularTexture.dispose();
  37755. }
  37756. if (this._bumpTexture) {
  37757. this._bumpTexture.dispose();
  37758. }
  37759. if (this._lightmapTexture) {
  37760. this._lightmapTexture.dispose();
  37761. }
  37762. if (this._refractionTexture) {
  37763. this._refractionTexture.dispose();
  37764. }
  37765. }
  37766. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37767. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37768. }
  37769. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37770. };
  37771. StandardMaterial.prototype.clone = function (name) {
  37772. var _this = this;
  37773. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37774. result.name = name;
  37775. result.id = name;
  37776. return result;
  37777. };
  37778. StandardMaterial.prototype.serialize = function () {
  37779. return BABYLON.SerializationHelper.Serialize(this);
  37780. };
  37781. // Statics
  37782. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37783. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37784. };
  37785. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37786. get: function () {
  37787. return StandardMaterial._DiffuseTextureEnabled;
  37788. },
  37789. set: function (value) {
  37790. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37791. return;
  37792. }
  37793. StandardMaterial._DiffuseTextureEnabled = value;
  37794. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37795. },
  37796. enumerable: true,
  37797. configurable: true
  37798. });
  37799. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37800. get: function () {
  37801. return StandardMaterial._AmbientTextureEnabled;
  37802. },
  37803. set: function (value) {
  37804. if (StandardMaterial._AmbientTextureEnabled === value) {
  37805. return;
  37806. }
  37807. StandardMaterial._AmbientTextureEnabled = value;
  37808. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37809. },
  37810. enumerable: true,
  37811. configurable: true
  37812. });
  37813. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37814. get: function () {
  37815. return StandardMaterial._OpacityTextureEnabled;
  37816. },
  37817. set: function (value) {
  37818. if (StandardMaterial._OpacityTextureEnabled === value) {
  37819. return;
  37820. }
  37821. StandardMaterial._OpacityTextureEnabled = value;
  37822. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37828. get: function () {
  37829. return StandardMaterial._ReflectionTextureEnabled;
  37830. },
  37831. set: function (value) {
  37832. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37833. return;
  37834. }
  37835. StandardMaterial._ReflectionTextureEnabled = value;
  37836. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37837. },
  37838. enumerable: true,
  37839. configurable: true
  37840. });
  37841. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37842. get: function () {
  37843. return StandardMaterial._EmissiveTextureEnabled;
  37844. },
  37845. set: function (value) {
  37846. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37847. return;
  37848. }
  37849. StandardMaterial._EmissiveTextureEnabled = value;
  37850. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37851. },
  37852. enumerable: true,
  37853. configurable: true
  37854. });
  37855. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37856. get: function () {
  37857. return StandardMaterial._SpecularTextureEnabled;
  37858. },
  37859. set: function (value) {
  37860. if (StandardMaterial._SpecularTextureEnabled === value) {
  37861. return;
  37862. }
  37863. StandardMaterial._SpecularTextureEnabled = value;
  37864. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37865. },
  37866. enumerable: true,
  37867. configurable: true
  37868. });
  37869. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37870. get: function () {
  37871. return StandardMaterial._BumpTextureEnabled;
  37872. },
  37873. set: function (value) {
  37874. if (StandardMaterial._BumpTextureEnabled === value) {
  37875. return;
  37876. }
  37877. StandardMaterial._BumpTextureEnabled = value;
  37878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37879. },
  37880. enumerable: true,
  37881. configurable: true
  37882. });
  37883. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37884. get: function () {
  37885. return StandardMaterial._LightmapTextureEnabled;
  37886. },
  37887. set: function (value) {
  37888. if (StandardMaterial._LightmapTextureEnabled === value) {
  37889. return;
  37890. }
  37891. StandardMaterial._LightmapTextureEnabled = value;
  37892. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37893. },
  37894. enumerable: true,
  37895. configurable: true
  37896. });
  37897. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37898. get: function () {
  37899. return StandardMaterial._RefractionTextureEnabled;
  37900. },
  37901. set: function (value) {
  37902. if (StandardMaterial._RefractionTextureEnabled === value) {
  37903. return;
  37904. }
  37905. StandardMaterial._RefractionTextureEnabled = value;
  37906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37907. },
  37908. enumerable: true,
  37909. configurable: true
  37910. });
  37911. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37912. get: function () {
  37913. return StandardMaterial._ColorGradingTextureEnabled;
  37914. },
  37915. set: function (value) {
  37916. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37917. return;
  37918. }
  37919. StandardMaterial._ColorGradingTextureEnabled = value;
  37920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37921. },
  37922. enumerable: true,
  37923. configurable: true
  37924. });
  37925. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37926. get: function () {
  37927. return StandardMaterial._FresnelEnabled;
  37928. },
  37929. set: function (value) {
  37930. if (StandardMaterial._FresnelEnabled === value) {
  37931. return;
  37932. }
  37933. StandardMaterial._FresnelEnabled = value;
  37934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37935. },
  37936. enumerable: true,
  37937. configurable: true
  37938. });
  37939. // Flags used to enable or disable a type of texture for all Standard Materials
  37940. StandardMaterial._DiffuseTextureEnabled = true;
  37941. StandardMaterial._AmbientTextureEnabled = true;
  37942. StandardMaterial._OpacityTextureEnabled = true;
  37943. StandardMaterial._ReflectionTextureEnabled = true;
  37944. StandardMaterial._EmissiveTextureEnabled = true;
  37945. StandardMaterial._SpecularTextureEnabled = true;
  37946. StandardMaterial._BumpTextureEnabled = true;
  37947. StandardMaterial._LightmapTextureEnabled = true;
  37948. StandardMaterial._RefractionTextureEnabled = true;
  37949. StandardMaterial._ColorGradingTextureEnabled = true;
  37950. StandardMaterial._FresnelEnabled = true;
  37951. __decorate([
  37952. BABYLON.serializeAsTexture("diffuseTexture")
  37953. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37954. __decorate([
  37955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37956. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37957. __decorate([
  37958. BABYLON.serializeAsTexture("ambientTexture")
  37959. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37960. __decorate([
  37961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37962. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37963. __decorate([
  37964. BABYLON.serializeAsTexture("opacityTexture")
  37965. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37966. __decorate([
  37967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37968. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37969. __decorate([
  37970. BABYLON.serializeAsTexture("reflectionTexture")
  37971. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37972. __decorate([
  37973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37974. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37975. __decorate([
  37976. BABYLON.serializeAsTexture("emissiveTexture")
  37977. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37978. __decorate([
  37979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37980. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37981. __decorate([
  37982. BABYLON.serializeAsTexture("specularTexture")
  37983. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37984. __decorate([
  37985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37986. ], StandardMaterial.prototype, "specularTexture", void 0);
  37987. __decorate([
  37988. BABYLON.serializeAsTexture("bumpTexture")
  37989. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37990. __decorate([
  37991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37992. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37993. __decorate([
  37994. BABYLON.serializeAsTexture("lightmapTexture")
  37995. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37996. __decorate([
  37997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37998. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37999. __decorate([
  38000. BABYLON.serializeAsTexture("refractionTexture")
  38001. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  38002. __decorate([
  38003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38004. ], StandardMaterial.prototype, "refractionTexture", void 0);
  38005. __decorate([
  38006. BABYLON.serializeAsColor3("ambient")
  38007. ], StandardMaterial.prototype, "ambientColor", void 0);
  38008. __decorate([
  38009. BABYLON.serializeAsColor3("diffuse")
  38010. ], StandardMaterial.prototype, "diffuseColor", void 0);
  38011. __decorate([
  38012. BABYLON.serializeAsColor3("specular")
  38013. ], StandardMaterial.prototype, "specularColor", void 0);
  38014. __decorate([
  38015. BABYLON.serializeAsColor3("emissive")
  38016. ], StandardMaterial.prototype, "emissiveColor", void 0);
  38017. __decorate([
  38018. BABYLON.serialize()
  38019. ], StandardMaterial.prototype, "specularPower", void 0);
  38020. __decorate([
  38021. BABYLON.serialize("useAlphaFromDiffuseTexture")
  38022. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  38023. __decorate([
  38024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38025. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  38026. __decorate([
  38027. BABYLON.serialize("useEmissiveAsIllumination")
  38028. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  38029. __decorate([
  38030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38031. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  38032. __decorate([
  38033. BABYLON.serialize("linkEmissiveWithDiffuse")
  38034. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  38035. __decorate([
  38036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38037. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  38038. __decorate([
  38039. BABYLON.serialize("useSpecularOverAlpha")
  38040. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  38041. __decorate([
  38042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38043. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  38044. __decorate([
  38045. BABYLON.serialize("useReflectionOverAlpha")
  38046. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  38047. __decorate([
  38048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38049. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  38050. __decorate([
  38051. BABYLON.serialize("disableLighting")
  38052. ], StandardMaterial.prototype, "_disableLighting", void 0);
  38053. __decorate([
  38054. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38055. ], StandardMaterial.prototype, "disableLighting", void 0);
  38056. __decorate([
  38057. BABYLON.serialize("useParallax")
  38058. ], StandardMaterial.prototype, "_useParallax", void 0);
  38059. __decorate([
  38060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38061. ], StandardMaterial.prototype, "useParallax", void 0);
  38062. __decorate([
  38063. BABYLON.serialize("useParallaxOcclusion")
  38064. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  38065. __decorate([
  38066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38067. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  38068. __decorate([
  38069. BABYLON.serialize()
  38070. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  38071. __decorate([
  38072. BABYLON.serialize("roughness")
  38073. ], StandardMaterial.prototype, "_roughness", void 0);
  38074. __decorate([
  38075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38076. ], StandardMaterial.prototype, "roughness", void 0);
  38077. __decorate([
  38078. BABYLON.serialize()
  38079. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  38080. __decorate([
  38081. BABYLON.serialize()
  38082. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  38083. __decorate([
  38084. BABYLON.serialize("useLightmapAsShadowmap")
  38085. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  38086. __decorate([
  38087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38088. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38089. __decorate([
  38090. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  38091. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  38092. __decorate([
  38093. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38094. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  38095. __decorate([
  38096. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  38097. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  38098. __decorate([
  38099. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  38100. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  38101. __decorate([
  38102. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  38103. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  38104. __decorate([
  38105. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38106. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  38107. __decorate([
  38108. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  38109. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  38110. __decorate([
  38111. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38112. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  38113. __decorate([
  38114. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  38115. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  38116. __decorate([
  38117. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38118. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  38119. __decorate([
  38120. BABYLON.serialize("useReflectionFresnelFromSpecular")
  38121. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  38122. __decorate([
  38123. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38124. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  38125. __decorate([
  38126. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  38127. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  38128. __decorate([
  38129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38130. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  38131. __decorate([
  38132. BABYLON.serialize("maxSimultaneousLights")
  38133. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  38134. __decorate([
  38135. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38136. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  38137. __decorate([
  38138. BABYLON.serialize("invertNormalMapX")
  38139. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  38140. __decorate([
  38141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38142. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  38143. __decorate([
  38144. BABYLON.serialize("invertNormalMapY")
  38145. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  38146. __decorate([
  38147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38148. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  38149. __decorate([
  38150. BABYLON.serialize("twoSidedLighting")
  38151. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  38152. __decorate([
  38153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38154. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  38155. __decorate([
  38156. BABYLON.serialize()
  38157. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  38158. return StandardMaterial;
  38159. }(BABYLON.PushMaterial));
  38160. BABYLON.StandardMaterial = StandardMaterial;
  38161. })(BABYLON || (BABYLON = {}));
  38162. //# sourceMappingURL=babylon.standardMaterial.js.map
  38163. var BABYLON;
  38164. (function (BABYLON) {
  38165. var PBRMaterialDefines = /** @class */ (function (_super) {
  38166. __extends(PBRMaterialDefines, _super);
  38167. function PBRMaterialDefines() {
  38168. var _this = _super.call(this) || this;
  38169. _this.PBR = true;
  38170. _this.MAINUV1 = false;
  38171. _this.MAINUV2 = false;
  38172. _this.UV1 = false;
  38173. _this.UV2 = false;
  38174. _this.ALBEDO = false;
  38175. _this.ALBEDODIRECTUV = 0;
  38176. _this.VERTEXCOLOR = false;
  38177. _this.AMBIENT = false;
  38178. _this.AMBIENTDIRECTUV = 0;
  38179. _this.AMBIENTINGRAYSCALE = false;
  38180. _this.OPACITY = false;
  38181. _this.VERTEXALPHA = false;
  38182. _this.OPACITYDIRECTUV = 0;
  38183. _this.OPACITYRGB = false;
  38184. _this.ALPHATEST = false;
  38185. _this.DEPTHPREPASS = false;
  38186. _this.ALPHABLEND = false;
  38187. _this.ALPHAFROMALBEDO = false;
  38188. _this.ALPHATESTVALUE = 0.5;
  38189. _this.SPECULAROVERALPHA = false;
  38190. _this.RADIANCEOVERALPHA = false;
  38191. _this.ALPHAFRESNEL = false;
  38192. _this.LINEARALPHAFRESNEL = false;
  38193. _this.PREMULTIPLYALPHA = false;
  38194. _this.EMISSIVE = false;
  38195. _this.EMISSIVEDIRECTUV = 0;
  38196. _this.REFLECTIVITY = false;
  38197. _this.REFLECTIVITYDIRECTUV = 0;
  38198. _this.SPECULARTERM = false;
  38199. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38200. _this.MICROSURFACEAUTOMATIC = false;
  38201. _this.LODBASEDMICROSFURACE = false;
  38202. _this.MICROSURFACEMAP = false;
  38203. _this.MICROSURFACEMAPDIRECTUV = 0;
  38204. _this.METALLICWORKFLOW = false;
  38205. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38206. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38207. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38208. _this.AOSTOREINMETALMAPRED = false;
  38209. _this.ENVIRONMENTBRDF = false;
  38210. _this.NORMAL = false;
  38211. _this.TANGENT = false;
  38212. _this.BUMP = false;
  38213. _this.BUMPDIRECTUV = 0;
  38214. _this.PARALLAX = false;
  38215. _this.PARALLAXOCCLUSION = false;
  38216. _this.NORMALXYSCALE = true;
  38217. _this.LIGHTMAP = false;
  38218. _this.LIGHTMAPDIRECTUV = 0;
  38219. _this.USELIGHTMAPASSHADOWMAP = false;
  38220. _this.REFLECTION = false;
  38221. _this.REFLECTIONMAP_3D = false;
  38222. _this.REFLECTIONMAP_SPHERICAL = false;
  38223. _this.REFLECTIONMAP_PLANAR = false;
  38224. _this.REFLECTIONMAP_CUBIC = false;
  38225. _this.REFLECTIONMAP_PROJECTION = false;
  38226. _this.REFLECTIONMAP_SKYBOX = false;
  38227. _this.REFLECTIONMAP_EXPLICIT = false;
  38228. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38229. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38230. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38231. _this.INVERTCUBICMAP = false;
  38232. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38233. _this.USESPHERICALINVERTEX = false;
  38234. _this.REFLECTIONMAP_OPPOSITEZ = false;
  38235. _this.LODINREFLECTIONALPHA = false;
  38236. _this.GAMMAREFLECTION = false;
  38237. _this.RADIANCEOCCLUSION = false;
  38238. _this.HORIZONOCCLUSION = false;
  38239. _this.REFRACTION = false;
  38240. _this.REFRACTIONMAP_3D = false;
  38241. _this.REFRACTIONMAP_OPPOSITEZ = false;
  38242. _this.LODINREFRACTIONALPHA = false;
  38243. _this.GAMMAREFRACTION = false;
  38244. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38245. _this.INSTANCES = false;
  38246. _this.NUM_BONE_INFLUENCERS = 0;
  38247. _this.BonesPerMesh = 0;
  38248. _this.NONUNIFORMSCALING = false;
  38249. _this.MORPHTARGETS = false;
  38250. _this.MORPHTARGETS_NORMAL = false;
  38251. _this.MORPHTARGETS_TANGENT = false;
  38252. _this.NUM_MORPH_INFLUENCERS = 0;
  38253. _this.IMAGEPROCESSING = false;
  38254. _this.VIGNETTE = false;
  38255. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38256. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38257. _this.TONEMAPPING = false;
  38258. _this.CONTRAST = false;
  38259. _this.COLORCURVES = false;
  38260. _this.COLORGRADING = false;
  38261. _this.COLORGRADING3D = false;
  38262. _this.SAMPLER3DGREENDEPTH = false;
  38263. _this.SAMPLER3DBGRMAP = false;
  38264. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38265. _this.EXPOSURE = false;
  38266. _this.USEPHYSICALLIGHTFALLOFF = false;
  38267. _this.TWOSIDEDLIGHTING = false;
  38268. _this.SHADOWFLOAT = false;
  38269. _this.CLIPPLANE = false;
  38270. _this.POINTSIZE = false;
  38271. _this.FOG = false;
  38272. _this.LOGARITHMICDEPTH = false;
  38273. _this.FORCENORMALFORWARD = false;
  38274. _this.rebuild();
  38275. return _this;
  38276. }
  38277. PBRMaterialDefines.prototype.reset = function () {
  38278. _super.prototype.reset.call(this);
  38279. this.ALPHATESTVALUE = 0.5;
  38280. this.PBR = true;
  38281. };
  38282. return PBRMaterialDefines;
  38283. }(BABYLON.MaterialDefines));
  38284. /**
  38285. * The Physically based material base class of BJS.
  38286. *
  38287. * This offers the main features of a standard PBR material.
  38288. * For more information, please refer to the documentation :
  38289. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38290. */
  38291. var PBRBaseMaterial = /** @class */ (function (_super) {
  38292. __extends(PBRBaseMaterial, _super);
  38293. /**
  38294. * Instantiates a new PBRMaterial instance.
  38295. *
  38296. * @param name The material name
  38297. * @param scene The scene the material will be use in.
  38298. */
  38299. function PBRBaseMaterial(name, scene) {
  38300. var _this = _super.call(this, name, scene) || this;
  38301. /**
  38302. * Intensity of the direct lights e.g. the four lights available in your scene.
  38303. * This impacts both the direct diffuse and specular highlights.
  38304. */
  38305. _this._directIntensity = 1.0;
  38306. /**
  38307. * Intensity of the emissive part of the material.
  38308. * This helps controlling the emissive effect without modifying the emissive color.
  38309. */
  38310. _this._emissiveIntensity = 1.0;
  38311. /**
  38312. * Intensity of the environment e.g. how much the environment will light the object
  38313. * either through harmonics for rough material or through the refelction for shiny ones.
  38314. */
  38315. _this._environmentIntensity = 1.0;
  38316. /**
  38317. * This is a special control allowing the reduction of the specular highlights coming from the
  38318. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38319. */
  38320. _this._specularIntensity = 1.0;
  38321. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38322. /**
  38323. * Debug Control allowing disabling the bump map on this material.
  38324. */
  38325. _this._disableBumpMap = false;
  38326. /**
  38327. * AKA Occlusion Texture Intensity in other nomenclature.
  38328. */
  38329. _this._ambientTextureStrength = 1.0;
  38330. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38331. /**
  38332. * AKA Diffuse Color in other nomenclature.
  38333. */
  38334. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38335. /**
  38336. * AKA Specular Color in other nomenclature.
  38337. */
  38338. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38339. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38340. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38341. /**
  38342. * AKA Glossiness in other nomenclature.
  38343. */
  38344. _this._microSurface = 0.9;
  38345. /**
  38346. * source material index of refraction (IOR)' / 'destination material IOR.
  38347. */
  38348. _this._indexOfRefraction = 0.66;
  38349. /**
  38350. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38351. */
  38352. _this._invertRefractionY = false;
  38353. /**
  38354. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38355. * Materials half opaque for instance using refraction could benefit from this control.
  38356. */
  38357. _this._linkRefractionWithTransparency = false;
  38358. _this._useLightmapAsShadowmap = false;
  38359. /**
  38360. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38361. * makes the reflect vector face the model (under horizon).
  38362. */
  38363. _this._useHorizonOcclusion = true;
  38364. /**
  38365. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38366. * too much the area relying on ambient texture to define their ambient occlusion.
  38367. */
  38368. _this._useRadianceOcclusion = true;
  38369. /**
  38370. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38371. */
  38372. _this._useAlphaFromAlbedoTexture = false;
  38373. /**
  38374. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38375. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38376. */
  38377. _this._useSpecularOverAlpha = true;
  38378. /**
  38379. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38380. */
  38381. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38382. /**
  38383. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38384. */
  38385. _this._useRoughnessFromMetallicTextureAlpha = true;
  38386. /**
  38387. * Specifies if the metallic texture contains the roughness information in its green channel.
  38388. */
  38389. _this._useRoughnessFromMetallicTextureGreen = false;
  38390. /**
  38391. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38392. */
  38393. _this._useMetallnessFromMetallicTextureBlue = false;
  38394. /**
  38395. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38396. */
  38397. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38398. /**
  38399. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38400. */
  38401. _this._useAmbientInGrayScale = false;
  38402. /**
  38403. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38404. * The material will try to infer what glossiness each pixel should be.
  38405. */
  38406. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38407. /**
  38408. * BJS is using an harcoded light falloff based on a manually sets up range.
  38409. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38410. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38411. */
  38412. _this._usePhysicalLightFalloff = true;
  38413. /**
  38414. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38415. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38416. */
  38417. _this._useRadianceOverAlpha = true;
  38418. /**
  38419. * Allows using the bump map in parallax mode.
  38420. */
  38421. _this._useParallax = false;
  38422. /**
  38423. * Allows using the bump map in parallax occlusion mode.
  38424. */
  38425. _this._useParallaxOcclusion = false;
  38426. /**
  38427. * Controls the scale bias of the parallax mode.
  38428. */
  38429. _this._parallaxScaleBias = 0.05;
  38430. /**
  38431. * If sets to true, disables all the lights affecting the material.
  38432. */
  38433. _this._disableLighting = false;
  38434. /**
  38435. * Number of Simultaneous lights allowed on the material.
  38436. */
  38437. _this._maxSimultaneousLights = 4;
  38438. /**
  38439. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38440. */
  38441. _this._invertNormalMapX = false;
  38442. /**
  38443. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38444. */
  38445. _this._invertNormalMapY = false;
  38446. /**
  38447. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38448. */
  38449. _this._twoSidedLighting = false;
  38450. /**
  38451. * Defines the alpha limits in alpha test mode.
  38452. */
  38453. _this._alphaCutOff = 0.4;
  38454. /**
  38455. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38456. */
  38457. _this._forceAlphaTest = false;
  38458. /**
  38459. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38460. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38461. */
  38462. _this._useAlphaFresnel = false;
  38463. /**
  38464. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38465. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38466. */
  38467. _this._useLinearAlphaFresnel = false;
  38468. /**
  38469. * The transparency mode of the material.
  38470. */
  38471. _this._transparencyMode = null;
  38472. /**
  38473. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38474. * from cos thetav and roughness:
  38475. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38476. */
  38477. _this._environmentBRDFTexture = null;
  38478. /**
  38479. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38480. */
  38481. _this._forceIrradianceInFragment = false;
  38482. /**
  38483. * Force normal to face away from face.
  38484. */
  38485. _this._forceNormalForward = false;
  38486. /**
  38487. * Force metallic workflow.
  38488. */
  38489. _this._forceMetallicWorkflow = false;
  38490. _this._renderTargets = new BABYLON.SmartArray(16);
  38491. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38492. // Setup the default processing configuration to the scene.
  38493. _this._attachImageProcessingConfiguration(null);
  38494. _this.getRenderTargetTextures = function () {
  38495. _this._renderTargets.reset();
  38496. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38497. _this._renderTargets.push(_this._reflectionTexture);
  38498. }
  38499. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38500. _this._renderTargets.push(_this._refractionTexture);
  38501. }
  38502. return _this._renderTargets;
  38503. };
  38504. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38505. return _this;
  38506. }
  38507. /**
  38508. * Attaches a new image processing configuration to the PBR Material.
  38509. * @param configuration
  38510. */
  38511. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38512. var _this = this;
  38513. if (configuration === this._imageProcessingConfiguration) {
  38514. return;
  38515. }
  38516. // Detaches observer.
  38517. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38518. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38519. }
  38520. // Pick the scene configuration if needed.
  38521. if (!configuration) {
  38522. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38523. }
  38524. else {
  38525. this._imageProcessingConfiguration = configuration;
  38526. }
  38527. // Attaches observer.
  38528. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38529. _this._markAllSubMeshesAsImageProcessingDirty();
  38530. });
  38531. };
  38532. PBRBaseMaterial.prototype.getClassName = function () {
  38533. return "PBRBaseMaterial";
  38534. };
  38535. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38536. get: function () {
  38537. return this._useLogarithmicDepth;
  38538. },
  38539. set: function (value) {
  38540. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38541. },
  38542. enumerable: true,
  38543. configurable: true
  38544. });
  38545. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38546. /**
  38547. * Gets the current transparency mode.
  38548. */
  38549. get: function () {
  38550. return this._transparencyMode;
  38551. },
  38552. /**
  38553. * Sets the transparency mode of the material.
  38554. */
  38555. set: function (value) {
  38556. if (this._transparencyMode === value) {
  38557. return;
  38558. }
  38559. this._transparencyMode = value;
  38560. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38561. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38562. },
  38563. enumerable: true,
  38564. configurable: true
  38565. });
  38566. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38567. /**
  38568. * Returns true if alpha blending should be disabled.
  38569. */
  38570. get: function () {
  38571. return (this._linkRefractionWithTransparency ||
  38572. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38573. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38574. },
  38575. enumerable: true,
  38576. configurable: true
  38577. });
  38578. /**
  38579. * Specifies whether or not this material should be rendered in alpha blend mode.
  38580. */
  38581. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38582. if (this._disableAlphaBlending) {
  38583. return false;
  38584. }
  38585. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38586. };
  38587. /**
  38588. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38589. */
  38590. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38591. if (this._disableAlphaBlending) {
  38592. return false;
  38593. }
  38594. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38595. };
  38596. /**
  38597. * Specifies whether or not this material should be rendered in alpha test mode.
  38598. */
  38599. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38600. if (this._forceAlphaTest) {
  38601. return true;
  38602. }
  38603. if (this._linkRefractionWithTransparency) {
  38604. return false;
  38605. }
  38606. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38607. };
  38608. /**
  38609. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38610. */
  38611. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38612. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38613. };
  38614. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38615. return this._albedoTexture;
  38616. };
  38617. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38618. var _this = this;
  38619. if (subMesh.effect && this.isFrozen) {
  38620. if (this._wasPreviouslyReady) {
  38621. return true;
  38622. }
  38623. }
  38624. if (!subMesh._materialDefines) {
  38625. subMesh._materialDefines = new PBRMaterialDefines();
  38626. }
  38627. var scene = this.getScene();
  38628. var defines = subMesh._materialDefines;
  38629. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38630. if (defines._renderId === scene.getRenderId()) {
  38631. return true;
  38632. }
  38633. }
  38634. var engine = scene.getEngine();
  38635. // Lights
  38636. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38637. defines._needNormals = true;
  38638. // Textures
  38639. if (defines._areTexturesDirty) {
  38640. defines._needUVs = false;
  38641. if (scene.texturesEnabled) {
  38642. if (scene.getEngine().getCaps().textureLOD) {
  38643. defines.LODBASEDMICROSFURACE = true;
  38644. }
  38645. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38646. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38647. return false;
  38648. }
  38649. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38650. }
  38651. else {
  38652. defines.ALBEDO = false;
  38653. }
  38654. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38655. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38656. return false;
  38657. }
  38658. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38659. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38660. }
  38661. else {
  38662. defines.AMBIENT = false;
  38663. }
  38664. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38665. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38666. return false;
  38667. }
  38668. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38669. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38670. }
  38671. else {
  38672. defines.OPACITY = false;
  38673. }
  38674. var reflectionTexture = this._getReflectionTexture();
  38675. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38676. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38677. return false;
  38678. }
  38679. defines.REFLECTION = true;
  38680. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38681. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38682. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38683. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38684. defines.INVERTCUBICMAP = true;
  38685. }
  38686. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38687. switch (reflectionTexture.coordinatesMode) {
  38688. case BABYLON.Texture.CUBIC_MODE:
  38689. case BABYLON.Texture.INVCUBIC_MODE:
  38690. defines.REFLECTIONMAP_CUBIC = true;
  38691. break;
  38692. case BABYLON.Texture.EXPLICIT_MODE:
  38693. defines.REFLECTIONMAP_EXPLICIT = true;
  38694. break;
  38695. case BABYLON.Texture.PLANAR_MODE:
  38696. defines.REFLECTIONMAP_PLANAR = true;
  38697. break;
  38698. case BABYLON.Texture.PROJECTION_MODE:
  38699. defines.REFLECTIONMAP_PROJECTION = true;
  38700. break;
  38701. case BABYLON.Texture.SKYBOX_MODE:
  38702. defines.REFLECTIONMAP_SKYBOX = true;
  38703. break;
  38704. case BABYLON.Texture.SPHERICAL_MODE:
  38705. defines.REFLECTIONMAP_SPHERICAL = true;
  38706. break;
  38707. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38708. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38709. break;
  38710. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38711. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38712. break;
  38713. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38714. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38715. break;
  38716. }
  38717. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38718. if (reflectionTexture.sphericalPolynomial) {
  38719. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38720. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38721. defines.USESPHERICALINVERTEX = false;
  38722. }
  38723. else {
  38724. defines.USESPHERICALINVERTEX = true;
  38725. }
  38726. }
  38727. }
  38728. }
  38729. else {
  38730. defines.REFLECTION = false;
  38731. defines.REFLECTIONMAP_3D = false;
  38732. defines.REFLECTIONMAP_SPHERICAL = false;
  38733. defines.REFLECTIONMAP_PLANAR = false;
  38734. defines.REFLECTIONMAP_CUBIC = false;
  38735. defines.REFLECTIONMAP_PROJECTION = false;
  38736. defines.REFLECTIONMAP_SKYBOX = false;
  38737. defines.REFLECTIONMAP_EXPLICIT = false;
  38738. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38739. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38740. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38741. defines.INVERTCUBICMAP = false;
  38742. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38743. defines.USESPHERICALINVERTEX = false;
  38744. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38745. defines.LODINREFLECTIONALPHA = false;
  38746. defines.GAMMAREFLECTION = false;
  38747. }
  38748. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38749. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38750. return false;
  38751. }
  38752. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38753. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38754. }
  38755. else {
  38756. defines.LIGHTMAP = false;
  38757. }
  38758. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38759. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38760. return false;
  38761. }
  38762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38763. }
  38764. else {
  38765. defines.EMISSIVE = false;
  38766. }
  38767. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38768. if (this._metallicTexture) {
  38769. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38770. return false;
  38771. }
  38772. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38773. defines.METALLICWORKFLOW = true;
  38774. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38775. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38776. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38777. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38778. }
  38779. else if (this._reflectivityTexture) {
  38780. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38781. return false;
  38782. }
  38783. defines.METALLICWORKFLOW = false;
  38784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38785. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38786. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38787. }
  38788. else {
  38789. defines.METALLICWORKFLOW = false;
  38790. defines.REFLECTIVITY = false;
  38791. }
  38792. if (this._microSurfaceTexture) {
  38793. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38794. return false;
  38795. }
  38796. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38797. }
  38798. else {
  38799. defines.MICROSURFACEMAP = false;
  38800. }
  38801. }
  38802. else {
  38803. defines.REFLECTIVITY = false;
  38804. defines.MICROSURFACEMAP = false;
  38805. }
  38806. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38807. // Bump texure can not be none blocking.
  38808. if (!this._bumpTexture.isReady()) {
  38809. return false;
  38810. }
  38811. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38812. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38813. defines.PARALLAX = true;
  38814. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38815. }
  38816. else {
  38817. defines.PARALLAX = false;
  38818. }
  38819. }
  38820. else {
  38821. defines.BUMP = false;
  38822. }
  38823. var refractionTexture = this._getRefractionTexture();
  38824. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38825. if (!refractionTexture.isReadyOrNotBlocking()) {
  38826. return false;
  38827. }
  38828. defines.REFRACTION = true;
  38829. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38830. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38831. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38832. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38833. if (this._linkRefractionWithTransparency) {
  38834. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38835. }
  38836. }
  38837. else {
  38838. defines.REFRACTION = false;
  38839. }
  38840. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38841. // This is blocking.
  38842. if (!this._environmentBRDFTexture.isReady()) {
  38843. return false;
  38844. }
  38845. defines.ENVIRONMENTBRDF = true;
  38846. }
  38847. else {
  38848. defines.ENVIRONMENTBRDF = false;
  38849. }
  38850. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38851. defines.ALPHAFROMALBEDO = true;
  38852. }
  38853. else {
  38854. defines.ALPHAFROMALBEDO = false;
  38855. }
  38856. }
  38857. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38858. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38859. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38860. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38861. defines.METALLICWORKFLOW = true;
  38862. }
  38863. else {
  38864. defines.METALLICWORKFLOW = false;
  38865. }
  38866. if (!this.backFaceCulling && this._twoSidedLighting) {
  38867. defines.TWOSIDEDLIGHTING = true;
  38868. }
  38869. else {
  38870. defines.TWOSIDEDLIGHTING = false;
  38871. }
  38872. defines.ALPHATESTVALUE = this._alphaCutOff;
  38873. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38874. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38875. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38876. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38877. }
  38878. if (defines._areImageProcessingDirty) {
  38879. if (!this._imageProcessingConfiguration.isReady()) {
  38880. return false;
  38881. }
  38882. this._imageProcessingConfiguration.prepareDefines(defines);
  38883. }
  38884. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38885. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38886. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38887. // Misc.
  38888. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  38889. // Values that need to be evaluated on every frame
  38890. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  38891. // Attribs
  38892. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38893. var bufferMesh = null;
  38894. if (mesh instanceof BABYLON.InstancedMesh) {
  38895. bufferMesh = mesh.sourceMesh;
  38896. }
  38897. else if (mesh instanceof BABYLON.Mesh) {
  38898. bufferMesh = mesh;
  38899. }
  38900. if (bufferMesh) {
  38901. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38902. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38903. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38904. var normals = normalVertexBuffer.getData();
  38905. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38906. var strideSize = normalVertexBuffer.getStrideSize();
  38907. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38908. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38909. defines.NORMAL = false;
  38910. }
  38911. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38912. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38913. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38914. var tangents = tangentVertexBuffer.getData();
  38915. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38916. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38917. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38918. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38919. defines.TANGENT = false;
  38920. }
  38921. }
  38922. }
  38923. else {
  38924. if (!scene.getEngine().getCaps().standardDerivatives) {
  38925. bufferMesh.createNormals(true);
  38926. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38927. }
  38928. }
  38929. }
  38930. }
  38931. // Get correct effect
  38932. if (defines.isDirty) {
  38933. defines.markAsProcessed();
  38934. scene.resetCachedMaterial();
  38935. // Fallbacks
  38936. var fallbacks = new BABYLON.EffectFallbacks();
  38937. var fallbackRank = 0;
  38938. if (defines.USESPHERICALINVERTEX) {
  38939. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38940. }
  38941. if (defines.FOG) {
  38942. fallbacks.addFallback(fallbackRank, "FOG");
  38943. }
  38944. if (defines.POINTSIZE) {
  38945. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38946. }
  38947. if (defines.LOGARITHMICDEPTH) {
  38948. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38949. }
  38950. if (defines.PARALLAX) {
  38951. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38952. }
  38953. if (defines.PARALLAXOCCLUSION) {
  38954. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38955. }
  38956. if (defines.ENVIRONMENTBRDF) {
  38957. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38958. }
  38959. if (defines.TANGENT) {
  38960. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38961. }
  38962. if (defines.BUMP) {
  38963. fallbacks.addFallback(fallbackRank++, "BUMP");
  38964. }
  38965. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38966. if (defines.SPECULARTERM) {
  38967. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38968. }
  38969. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38970. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38971. }
  38972. if (defines.LIGHTMAP) {
  38973. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38974. }
  38975. if (defines.NORMAL) {
  38976. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38977. }
  38978. if (defines.AMBIENT) {
  38979. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38980. }
  38981. if (defines.EMISSIVE) {
  38982. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38983. }
  38984. if (defines.VERTEXCOLOR) {
  38985. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38986. }
  38987. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38988. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38989. }
  38990. if (defines.MORPHTARGETS) {
  38991. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38992. }
  38993. //Attributes
  38994. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38995. if (defines.NORMAL) {
  38996. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38997. }
  38998. if (defines.TANGENT) {
  38999. attribs.push(BABYLON.VertexBuffer.TangentKind);
  39000. }
  39001. if (defines.UV1) {
  39002. attribs.push(BABYLON.VertexBuffer.UVKind);
  39003. }
  39004. if (defines.UV2) {
  39005. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39006. }
  39007. if (defines.VERTEXCOLOR) {
  39008. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39009. }
  39010. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39011. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39012. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39013. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39014. "vFogInfos", "vFogColor", "pointSize",
  39015. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39016. "mBones",
  39017. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39018. "vLightingIntensity",
  39019. "logarithmicDepthConstant",
  39020. "vSphericalX", "vSphericalY", "vSphericalZ",
  39021. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39022. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39023. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  39024. "vTangentSpaceParams"
  39025. ];
  39026. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  39027. "bumpSampler", "lightmapSampler", "opacitySampler",
  39028. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  39029. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  39030. "microSurfaceSampler", "environmentBrdfSampler"];
  39031. var uniformBuffers = ["Material", "Scene"];
  39032. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39033. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39034. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39035. uniformsNames: uniforms,
  39036. uniformBuffersNames: uniformBuffers,
  39037. samplers: samplers,
  39038. defines: defines,
  39039. maxSimultaneousLights: this._maxSimultaneousLights
  39040. });
  39041. var onCompiled = function (effect) {
  39042. if (_this.onCompiled) {
  39043. _this.onCompiled(effect);
  39044. }
  39045. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39046. };
  39047. var join = defines.toString();
  39048. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39049. attributes: attribs,
  39050. uniformsNames: uniforms,
  39051. uniformBuffersNames: uniformBuffers,
  39052. samplers: samplers,
  39053. defines: join,
  39054. fallbacks: fallbacks,
  39055. onCompiled: onCompiled,
  39056. onError: this.onError,
  39057. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39058. }, engine), defines);
  39059. this.buildUniformLayout();
  39060. }
  39061. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39062. return false;
  39063. }
  39064. defines._renderId = scene.getRenderId();
  39065. this._wasPreviouslyReady = true;
  39066. return true;
  39067. };
  39068. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39069. // Order is important !
  39070. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39071. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39072. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39073. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39074. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39075. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39076. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39077. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39078. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39079. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39080. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39081. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39082. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39083. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39084. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39085. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39086. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39087. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39088. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39089. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39090. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39091. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39092. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39093. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39094. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  39095. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  39096. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39097. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39098. this._uniformBuffer.addUniform("pointSize", 1);
  39099. this._uniformBuffer.create();
  39100. };
  39101. PBRBaseMaterial.prototype.unbind = function () {
  39102. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39103. this._uniformBuffer.setTexture("reflectionSampler", null);
  39104. }
  39105. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39106. this._uniformBuffer.setTexture("refractionSampler", null);
  39107. }
  39108. _super.prototype.unbind.call(this);
  39109. };
  39110. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39111. this._activeEffect.setMatrix("world", world);
  39112. };
  39113. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39114. var scene = this.getScene();
  39115. var defines = subMesh._materialDefines;
  39116. if (!defines) {
  39117. return;
  39118. }
  39119. var effect = subMesh.effect;
  39120. if (!effect) {
  39121. return;
  39122. }
  39123. this._activeEffect = effect;
  39124. // Matrices
  39125. this.bindOnlyWorldMatrix(world);
  39126. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39127. // Bones
  39128. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39129. var reflectionTexture = null;
  39130. if (mustRebind) {
  39131. this._uniformBuffer.bindToEffect(effect, "Material");
  39132. this.bindViewProjection(effect);
  39133. reflectionTexture = this._getReflectionTexture();
  39134. var refractionTexture = this._getRefractionTexture();
  39135. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39136. // Texture uniforms
  39137. if (scene.texturesEnabled) {
  39138. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39139. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39140. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  39141. }
  39142. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39143. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39144. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39145. }
  39146. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39147. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39148. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39149. }
  39150. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39151. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39152. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39153. var polynomials = reflectionTexture.sphericalPolynomial;
  39154. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  39155. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  39156. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  39157. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  39158. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  39159. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  39160. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  39161. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  39162. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  39163. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  39164. }
  39165. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  39166. }
  39167. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39168. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39169. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39170. }
  39171. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39172. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39173. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39174. }
  39175. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39176. if (this._metallicTexture) {
  39177. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39178. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  39179. }
  39180. else if (this._reflectivityTexture) {
  39181. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39182. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  39183. }
  39184. if (this._microSurfaceTexture) {
  39185. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39186. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  39187. }
  39188. }
  39189. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39190. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39191. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39192. if (scene._mirroredCameraPosition) {
  39193. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39194. }
  39195. else {
  39196. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39197. }
  39198. }
  39199. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39200. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  39201. var depth = 1.0;
  39202. if (!refractionTexture.isCube) {
  39203. if (refractionTexture.depth) {
  39204. depth = refractionTexture.depth;
  39205. }
  39206. }
  39207. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39208. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  39209. }
  39210. }
  39211. // Point size
  39212. if (this.pointsCloud) {
  39213. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39214. }
  39215. // Colors
  39216. if (defines.METALLICWORKFLOW) {
  39217. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39218. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39219. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39220. }
  39221. else {
  39222. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  39223. }
  39224. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  39225. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  39226. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  39227. // Misc
  39228. this._lightingInfos.x = this._directIntensity;
  39229. this._lightingInfos.y = this._emissiveIntensity;
  39230. this._lightingInfos.z = this._environmentIntensity;
  39231. this._lightingInfos.w = this._specularIntensity;
  39232. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39233. }
  39234. // Textures
  39235. if (scene.texturesEnabled) {
  39236. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39237. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39238. }
  39239. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39240. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39241. }
  39242. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39243. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39244. }
  39245. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39246. if (defines.LODBASEDMICROSFURACE) {
  39247. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  39248. }
  39249. else {
  39250. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  39251. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  39252. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  39253. }
  39254. }
  39255. if (defines.ENVIRONMENTBRDF) {
  39256. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  39257. }
  39258. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39259. if (defines.LODBASEDMICROSFURACE) {
  39260. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39261. }
  39262. else {
  39263. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39264. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39265. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39266. }
  39267. }
  39268. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39269. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39270. }
  39271. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39272. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39273. }
  39274. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39275. if (this._metallicTexture) {
  39276. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39277. }
  39278. else if (this._reflectivityTexture) {
  39279. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39280. }
  39281. if (this._microSurfaceTexture) {
  39282. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39283. }
  39284. }
  39285. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39286. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39287. }
  39288. }
  39289. // Clip plane
  39290. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39291. // Colors
  39292. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39293. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39294. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39295. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39296. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39297. }
  39298. if (mustRebind || !this.isFrozen) {
  39299. // Lights
  39300. if (scene.lightsEnabled && !this._disableLighting) {
  39301. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39302. }
  39303. // View
  39304. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39305. this.bindView(effect);
  39306. }
  39307. // Fog
  39308. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39309. // Morph targets
  39310. if (defines.NUM_MORPH_INFLUENCERS) {
  39311. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39312. }
  39313. // image processing
  39314. this._imageProcessingConfiguration.bind(this._activeEffect);
  39315. // Log. depth
  39316. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39317. }
  39318. this._uniformBuffer.update();
  39319. this._afterBind(mesh);
  39320. };
  39321. PBRBaseMaterial.prototype.getAnimatables = function () {
  39322. var results = [];
  39323. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39324. results.push(this._albedoTexture);
  39325. }
  39326. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39327. results.push(this._ambientTexture);
  39328. }
  39329. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39330. results.push(this._opacityTexture);
  39331. }
  39332. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39333. results.push(this._reflectionTexture);
  39334. }
  39335. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39336. results.push(this._emissiveTexture);
  39337. }
  39338. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39339. results.push(this._metallicTexture);
  39340. }
  39341. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39342. results.push(this._reflectivityTexture);
  39343. }
  39344. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39345. results.push(this._bumpTexture);
  39346. }
  39347. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39348. results.push(this._lightmapTexture);
  39349. }
  39350. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39351. results.push(this._refractionTexture);
  39352. }
  39353. return results;
  39354. };
  39355. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39356. if (this._reflectionTexture) {
  39357. return this._reflectionTexture;
  39358. }
  39359. return this.getScene().environmentTexture;
  39360. };
  39361. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39362. if (this._refractionTexture) {
  39363. return this._refractionTexture;
  39364. }
  39365. if (this._linkRefractionWithTransparency) {
  39366. return this.getScene().environmentTexture;
  39367. }
  39368. return null;
  39369. };
  39370. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39371. if (forceDisposeTextures) {
  39372. if (this._albedoTexture) {
  39373. this._albedoTexture.dispose();
  39374. }
  39375. if (this._ambientTexture) {
  39376. this._ambientTexture.dispose();
  39377. }
  39378. if (this._opacityTexture) {
  39379. this._opacityTexture.dispose();
  39380. }
  39381. if (this._reflectionTexture) {
  39382. this._reflectionTexture.dispose();
  39383. }
  39384. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39385. this._environmentBRDFTexture.dispose();
  39386. }
  39387. if (this._emissiveTexture) {
  39388. this._emissiveTexture.dispose();
  39389. }
  39390. if (this._metallicTexture) {
  39391. this._metallicTexture.dispose();
  39392. }
  39393. if (this._reflectivityTexture) {
  39394. this._reflectivityTexture.dispose();
  39395. }
  39396. if (this._bumpTexture) {
  39397. this._bumpTexture.dispose();
  39398. }
  39399. if (this._lightmapTexture) {
  39400. this._lightmapTexture.dispose();
  39401. }
  39402. if (this._refractionTexture) {
  39403. this._refractionTexture.dispose();
  39404. }
  39405. }
  39406. this._renderTargets.dispose();
  39407. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39408. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39409. }
  39410. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39411. };
  39412. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39413. __decorate([
  39414. BABYLON.serializeAsImageProcessingConfiguration()
  39415. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39416. __decorate([
  39417. BABYLON.serialize()
  39418. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39419. __decorate([
  39420. BABYLON.serialize()
  39421. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39422. return PBRBaseMaterial;
  39423. }(BABYLON.PushMaterial));
  39424. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39425. })(BABYLON || (BABYLON = {}));
  39426. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39427. var BABYLON;
  39428. (function (BABYLON) {
  39429. /**
  39430. * The Physically based simple base material of BJS.
  39431. *
  39432. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39433. * It is used as the base class for both the specGloss and metalRough conventions.
  39434. */
  39435. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39436. __extends(PBRBaseSimpleMaterial, _super);
  39437. /**
  39438. * Instantiates a new PBRMaterial instance.
  39439. *
  39440. * @param name The material name
  39441. * @param scene The scene the material will be use in.
  39442. */
  39443. function PBRBaseSimpleMaterial(name, scene) {
  39444. var _this = _super.call(this, name, scene) || this;
  39445. /**
  39446. * Number of Simultaneous lights allowed on the material.
  39447. */
  39448. _this.maxSimultaneousLights = 4;
  39449. /**
  39450. * If sets to true, disables all the lights affecting the material.
  39451. */
  39452. _this.disableLighting = false;
  39453. /**
  39454. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39455. */
  39456. _this.invertNormalMapX = false;
  39457. /**
  39458. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39459. */
  39460. _this.invertNormalMapY = false;
  39461. /**
  39462. * Emissivie color used to self-illuminate the model.
  39463. */
  39464. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39465. /**
  39466. * Occlusion Channel Strenght.
  39467. */
  39468. _this.occlusionStrength = 1.0;
  39469. _this.useLightmapAsShadowmap = false;
  39470. _this._useAlphaFromAlbedoTexture = true;
  39471. _this._useAmbientInGrayScale = true;
  39472. return _this;
  39473. }
  39474. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39475. /**
  39476. * Gets the current double sided mode.
  39477. */
  39478. get: function () {
  39479. return this._twoSidedLighting;
  39480. },
  39481. /**
  39482. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39483. */
  39484. set: function (value) {
  39485. if (this._twoSidedLighting === value) {
  39486. return;
  39487. }
  39488. this._twoSidedLighting = value;
  39489. this.backFaceCulling = !value;
  39490. this._markAllSubMeshesAsTexturesDirty();
  39491. },
  39492. enumerable: true,
  39493. configurable: true
  39494. });
  39495. /**
  39496. * Return the active textures of the material.
  39497. */
  39498. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39499. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39500. if (this.environmentTexture) {
  39501. activeTextures.push(this.environmentTexture);
  39502. }
  39503. if (this.normalTexture) {
  39504. activeTextures.push(this.normalTexture);
  39505. }
  39506. if (this.emissiveTexture) {
  39507. activeTextures.push(this.emissiveTexture);
  39508. }
  39509. if (this.occlusionTexture) {
  39510. activeTextures.push(this.occlusionTexture);
  39511. }
  39512. if (this.lightmapTexture) {
  39513. activeTextures.push(this.lightmapTexture);
  39514. }
  39515. return activeTextures;
  39516. };
  39517. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39518. if (_super.prototype.hasTexture.call(this, texture)) {
  39519. return true;
  39520. }
  39521. if (this.lightmapTexture === texture) {
  39522. return true;
  39523. }
  39524. return false;
  39525. };
  39526. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39527. return "PBRBaseSimpleMaterial";
  39528. };
  39529. __decorate([
  39530. BABYLON.serialize(),
  39531. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39532. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39533. __decorate([
  39534. BABYLON.serialize(),
  39535. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39536. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39537. __decorate([
  39538. BABYLON.serializeAsTexture(),
  39539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39540. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39541. __decorate([
  39542. BABYLON.serialize(),
  39543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39544. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39545. __decorate([
  39546. BABYLON.serialize(),
  39547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39548. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39549. __decorate([
  39550. BABYLON.serializeAsTexture(),
  39551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39552. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39553. __decorate([
  39554. BABYLON.serializeAsColor3("emissive"),
  39555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39556. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39557. __decorate([
  39558. BABYLON.serializeAsTexture(),
  39559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39560. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39561. __decorate([
  39562. BABYLON.serialize(),
  39563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39564. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39565. __decorate([
  39566. BABYLON.serializeAsTexture(),
  39567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39568. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39569. __decorate([
  39570. BABYLON.serialize(),
  39571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39572. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39573. __decorate([
  39574. BABYLON.serialize()
  39575. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39576. __decorate([
  39577. BABYLON.serializeAsTexture(),
  39578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39579. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39580. __decorate([
  39581. BABYLON.serialize(),
  39582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39583. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39584. return PBRBaseSimpleMaterial;
  39585. }(BABYLON.PBRBaseMaterial));
  39586. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39587. })(BABYLON || (BABYLON = {}));
  39588. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39589. var BABYLON;
  39590. (function (BABYLON) {
  39591. /**
  39592. * The Physically based material of BJS.
  39593. *
  39594. * This offers the main features of a standard PBR material.
  39595. * For more information, please refer to the documentation :
  39596. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39597. */
  39598. var PBRMaterial = /** @class */ (function (_super) {
  39599. __extends(PBRMaterial, _super);
  39600. /**
  39601. * Instantiates a new PBRMaterial instance.
  39602. *
  39603. * @param name The material name
  39604. * @param scene The scene the material will be use in.
  39605. */
  39606. function PBRMaterial(name, scene) {
  39607. var _this = _super.call(this, name, scene) || this;
  39608. /**
  39609. * Intensity of the direct lights e.g. the four lights available in your scene.
  39610. * This impacts both the direct diffuse and specular highlights.
  39611. */
  39612. _this.directIntensity = 1.0;
  39613. /**
  39614. * Intensity of the emissive part of the material.
  39615. * This helps controlling the emissive effect without modifying the emissive color.
  39616. */
  39617. _this.emissiveIntensity = 1.0;
  39618. /**
  39619. * Intensity of the environment e.g. how much the environment will light the object
  39620. * either through harmonics for rough material or through the refelction for shiny ones.
  39621. */
  39622. _this.environmentIntensity = 1.0;
  39623. /**
  39624. * This is a special control allowing the reduction of the specular highlights coming from the
  39625. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39626. */
  39627. _this.specularIntensity = 1.0;
  39628. /**
  39629. * Debug Control allowing disabling the bump map on this material.
  39630. */
  39631. _this.disableBumpMap = false;
  39632. /**
  39633. * AKA Occlusion Texture Intensity in other nomenclature.
  39634. */
  39635. _this.ambientTextureStrength = 1.0;
  39636. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39637. /**
  39638. * AKA Diffuse Color in other nomenclature.
  39639. */
  39640. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39641. /**
  39642. * AKA Specular Color in other nomenclature.
  39643. */
  39644. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39645. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39646. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39647. /**
  39648. * AKA Glossiness in other nomenclature.
  39649. */
  39650. _this.microSurface = 1.0;
  39651. /**
  39652. * source material index of refraction (IOR)' / 'destination material IOR.
  39653. */
  39654. _this.indexOfRefraction = 0.66;
  39655. /**
  39656. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39657. */
  39658. _this.invertRefractionY = false;
  39659. /**
  39660. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39661. * Materials half opaque for instance using refraction could benefit from this control.
  39662. */
  39663. _this.linkRefractionWithTransparency = false;
  39664. _this.useLightmapAsShadowmap = false;
  39665. /**
  39666. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39667. */
  39668. _this.useAlphaFromAlbedoTexture = false;
  39669. /**
  39670. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39671. */
  39672. _this.forceAlphaTest = false;
  39673. /**
  39674. * Defines the alpha limits in alpha test mode.
  39675. */
  39676. _this.alphaCutOff = 0.4;
  39677. /**
  39678. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39679. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39680. */
  39681. _this.useSpecularOverAlpha = true;
  39682. /**
  39683. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39684. */
  39685. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39686. /**
  39687. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39688. */
  39689. _this.useRoughnessFromMetallicTextureAlpha = true;
  39690. /**
  39691. * Specifies if the metallic texture contains the roughness information in its green channel.
  39692. */
  39693. _this.useRoughnessFromMetallicTextureGreen = false;
  39694. /**
  39695. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39696. */
  39697. _this.useMetallnessFromMetallicTextureBlue = false;
  39698. /**
  39699. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39700. */
  39701. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39702. /**
  39703. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39704. */
  39705. _this.useAmbientInGrayScale = false;
  39706. /**
  39707. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39708. * The material will try to infer what glossiness each pixel should be.
  39709. */
  39710. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39711. /**
  39712. * BJS is using an harcoded light falloff based on a manually sets up range.
  39713. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39714. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39715. */
  39716. _this.usePhysicalLightFalloff = true;
  39717. /**
  39718. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39719. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39720. */
  39721. _this.useRadianceOverAlpha = true;
  39722. /**
  39723. * Allows using the bump map in parallax mode.
  39724. */
  39725. _this.useParallax = false;
  39726. /**
  39727. * Allows using the bump map in parallax occlusion mode.
  39728. */
  39729. _this.useParallaxOcclusion = false;
  39730. /**
  39731. * Controls the scale bias of the parallax mode.
  39732. */
  39733. _this.parallaxScaleBias = 0.05;
  39734. /**
  39735. * If sets to true, disables all the lights affecting the material.
  39736. */
  39737. _this.disableLighting = false;
  39738. /**
  39739. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39740. */
  39741. _this.forceIrradianceInFragment = false;
  39742. /**
  39743. * Number of Simultaneous lights allowed on the material.
  39744. */
  39745. _this.maxSimultaneousLights = 4;
  39746. /**
  39747. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39748. */
  39749. _this.invertNormalMapX = false;
  39750. /**
  39751. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39752. */
  39753. _this.invertNormalMapY = false;
  39754. /**
  39755. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39756. */
  39757. _this.twoSidedLighting = false;
  39758. /**
  39759. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39760. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39761. */
  39762. _this.useAlphaFresnel = false;
  39763. /**
  39764. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39765. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39766. */
  39767. _this.useLinearAlphaFresnel = false;
  39768. /**
  39769. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39770. * And/Or occlude the blended part.
  39771. */
  39772. _this.environmentBRDFTexture = null;
  39773. /**
  39774. * Force normal to face away from face.
  39775. */
  39776. _this.forceNormalForward = false;
  39777. /**
  39778. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39779. * makes the reflect vector face the model (under horizon).
  39780. */
  39781. _this.useHorizonOcclusion = true;
  39782. /**
  39783. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39784. * too much the area relying on ambient texture to define their ambient occlusion.
  39785. */
  39786. _this.useRadianceOcclusion = true;
  39787. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39788. return _this;
  39789. }
  39790. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39791. /**
  39792. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39793. */
  39794. get: function () {
  39795. return this._PBRMATERIAL_OPAQUE;
  39796. },
  39797. enumerable: true,
  39798. configurable: true
  39799. });
  39800. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39801. /**
  39802. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39803. */
  39804. get: function () {
  39805. return this._PBRMATERIAL_ALPHATEST;
  39806. },
  39807. enumerable: true,
  39808. configurable: true
  39809. });
  39810. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39811. /**
  39812. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39813. */
  39814. get: function () {
  39815. return this._PBRMATERIAL_ALPHABLEND;
  39816. },
  39817. enumerable: true,
  39818. configurable: true
  39819. });
  39820. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39821. /**
  39822. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39823. * They are also discarded below the alpha cutoff threshold to improve performances.
  39824. */
  39825. get: function () {
  39826. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39827. },
  39828. enumerable: true,
  39829. configurable: true
  39830. });
  39831. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39832. /**
  39833. * Gets the image processing configuration used either in this material.
  39834. */
  39835. get: function () {
  39836. return this._imageProcessingConfiguration;
  39837. },
  39838. /**
  39839. * Sets the Default image processing configuration used either in the this material.
  39840. *
  39841. * If sets to null, the scene one is in use.
  39842. */
  39843. set: function (value) {
  39844. this._attachImageProcessingConfiguration(value);
  39845. // Ensure the effect will be rebuilt.
  39846. this._markAllSubMeshesAsTexturesDirty();
  39847. },
  39848. enumerable: true,
  39849. configurable: true
  39850. });
  39851. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39852. /**
  39853. * Gets wether the color curves effect is enabled.
  39854. */
  39855. get: function () {
  39856. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39857. },
  39858. /**
  39859. * Sets wether the color curves effect is enabled.
  39860. */
  39861. set: function (value) {
  39862. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39863. },
  39864. enumerable: true,
  39865. configurable: true
  39866. });
  39867. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39868. /**
  39869. * Gets wether the color grading effect is enabled.
  39870. */
  39871. get: function () {
  39872. return this.imageProcessingConfiguration.colorGradingEnabled;
  39873. },
  39874. /**
  39875. * Gets wether the color grading effect is enabled.
  39876. */
  39877. set: function (value) {
  39878. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39879. },
  39880. enumerable: true,
  39881. configurable: true
  39882. });
  39883. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39884. /**
  39885. * Gets wether tonemapping is enabled or not.
  39886. */
  39887. get: function () {
  39888. return this._imageProcessingConfiguration.toneMappingEnabled;
  39889. },
  39890. /**
  39891. * Sets wether tonemapping is enabled or not
  39892. */
  39893. set: function (value) {
  39894. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39895. },
  39896. enumerable: true,
  39897. configurable: true
  39898. });
  39899. ;
  39900. ;
  39901. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39902. /**
  39903. * The camera exposure used on this material.
  39904. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39905. * This corresponds to a photographic exposure.
  39906. */
  39907. get: function () {
  39908. return this._imageProcessingConfiguration.exposure;
  39909. },
  39910. /**
  39911. * The camera exposure used on this material.
  39912. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39913. * This corresponds to a photographic exposure.
  39914. */
  39915. set: function (value) {
  39916. this._imageProcessingConfiguration.exposure = value;
  39917. },
  39918. enumerable: true,
  39919. configurable: true
  39920. });
  39921. ;
  39922. ;
  39923. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39924. /**
  39925. * Gets The camera contrast used on this material.
  39926. */
  39927. get: function () {
  39928. return this._imageProcessingConfiguration.contrast;
  39929. },
  39930. /**
  39931. * Sets The camera contrast used on this material.
  39932. */
  39933. set: function (value) {
  39934. this._imageProcessingConfiguration.contrast = value;
  39935. },
  39936. enumerable: true,
  39937. configurable: true
  39938. });
  39939. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39940. /**
  39941. * Gets the Color Grading 2D Lookup Texture.
  39942. */
  39943. get: function () {
  39944. return this._imageProcessingConfiguration.colorGradingTexture;
  39945. },
  39946. /**
  39947. * Sets the Color Grading 2D Lookup Texture.
  39948. */
  39949. set: function (value) {
  39950. this._imageProcessingConfiguration.colorGradingTexture = value;
  39951. },
  39952. enumerable: true,
  39953. configurable: true
  39954. });
  39955. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39956. /**
  39957. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39958. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39959. * 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;
  39960. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39961. */
  39962. get: function () {
  39963. return this._imageProcessingConfiguration.colorCurves;
  39964. },
  39965. /**
  39966. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39967. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39968. * 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;
  39969. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39970. */
  39971. set: function (value) {
  39972. this._imageProcessingConfiguration.colorCurves = value;
  39973. },
  39974. enumerable: true,
  39975. configurable: true
  39976. });
  39977. PBRMaterial.prototype.getClassName = function () {
  39978. return "PBRMaterial";
  39979. };
  39980. PBRMaterial.prototype.getActiveTextures = function () {
  39981. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39982. if (this._albedoTexture) {
  39983. activeTextures.push(this._albedoTexture);
  39984. }
  39985. if (this._ambientTexture) {
  39986. activeTextures.push(this._ambientTexture);
  39987. }
  39988. if (this._opacityTexture) {
  39989. activeTextures.push(this._opacityTexture);
  39990. }
  39991. if (this._reflectionTexture) {
  39992. activeTextures.push(this._reflectionTexture);
  39993. }
  39994. if (this._emissiveTexture) {
  39995. activeTextures.push(this._emissiveTexture);
  39996. }
  39997. if (this._reflectivityTexture) {
  39998. activeTextures.push(this._reflectivityTexture);
  39999. }
  40000. if (this._metallicTexture) {
  40001. activeTextures.push(this._metallicTexture);
  40002. }
  40003. if (this._microSurfaceTexture) {
  40004. activeTextures.push(this._microSurfaceTexture);
  40005. }
  40006. if (this._bumpTexture) {
  40007. activeTextures.push(this._bumpTexture);
  40008. }
  40009. if (this._lightmapTexture) {
  40010. activeTextures.push(this._lightmapTexture);
  40011. }
  40012. if (this._refractionTexture) {
  40013. activeTextures.push(this._refractionTexture);
  40014. }
  40015. return activeTextures;
  40016. };
  40017. PBRMaterial.prototype.hasTexture = function (texture) {
  40018. if (_super.prototype.hasTexture.call(this, texture)) {
  40019. return true;
  40020. }
  40021. if (this._albedoTexture === texture) {
  40022. return true;
  40023. }
  40024. if (this._ambientTexture === texture) {
  40025. return true;
  40026. }
  40027. if (this._opacityTexture === texture) {
  40028. return true;
  40029. }
  40030. if (this._reflectionTexture === texture) {
  40031. return true;
  40032. }
  40033. if (this._reflectivityTexture === texture) {
  40034. return true;
  40035. }
  40036. if (this._metallicTexture === texture) {
  40037. return true;
  40038. }
  40039. if (this._microSurfaceTexture === texture) {
  40040. return true;
  40041. }
  40042. if (this._bumpTexture === texture) {
  40043. return true;
  40044. }
  40045. if (this._lightmapTexture === texture) {
  40046. return true;
  40047. }
  40048. if (this._refractionTexture === texture) {
  40049. return true;
  40050. }
  40051. return false;
  40052. };
  40053. PBRMaterial.prototype.clone = function (name) {
  40054. var _this = this;
  40055. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  40056. clone.id = name;
  40057. clone.name = name;
  40058. return clone;
  40059. };
  40060. PBRMaterial.prototype.serialize = function () {
  40061. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40062. serializationObject.customType = "BABYLON.PBRMaterial";
  40063. return serializationObject;
  40064. };
  40065. // Statics
  40066. PBRMaterial.Parse = function (source, scene, rootUrl) {
  40067. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  40068. };
  40069. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  40070. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  40071. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  40072. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  40073. __decorate([
  40074. BABYLON.serialize(),
  40075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40076. ], PBRMaterial.prototype, "directIntensity", void 0);
  40077. __decorate([
  40078. BABYLON.serialize(),
  40079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40080. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  40081. __decorate([
  40082. BABYLON.serialize(),
  40083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40084. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  40085. __decorate([
  40086. BABYLON.serialize(),
  40087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40088. ], PBRMaterial.prototype, "specularIntensity", void 0);
  40089. __decorate([
  40090. BABYLON.serialize(),
  40091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40092. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  40093. __decorate([
  40094. BABYLON.serializeAsTexture(),
  40095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40096. ], PBRMaterial.prototype, "albedoTexture", void 0);
  40097. __decorate([
  40098. BABYLON.serializeAsTexture(),
  40099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40100. ], PBRMaterial.prototype, "ambientTexture", void 0);
  40101. __decorate([
  40102. BABYLON.serialize(),
  40103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40104. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  40105. __decorate([
  40106. BABYLON.serializeAsTexture(),
  40107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40108. ], PBRMaterial.prototype, "opacityTexture", void 0);
  40109. __decorate([
  40110. BABYLON.serializeAsTexture(),
  40111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40112. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  40113. __decorate([
  40114. BABYLON.serializeAsTexture(),
  40115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40116. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  40117. __decorate([
  40118. BABYLON.serializeAsTexture(),
  40119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40120. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  40121. __decorate([
  40122. BABYLON.serializeAsTexture(),
  40123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40124. ], PBRMaterial.prototype, "metallicTexture", void 0);
  40125. __decorate([
  40126. BABYLON.serialize(),
  40127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40128. ], PBRMaterial.prototype, "metallic", void 0);
  40129. __decorate([
  40130. BABYLON.serialize(),
  40131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40132. ], PBRMaterial.prototype, "roughness", void 0);
  40133. __decorate([
  40134. BABYLON.serializeAsTexture(),
  40135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40136. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  40137. __decorate([
  40138. BABYLON.serializeAsTexture(),
  40139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40140. ], PBRMaterial.prototype, "bumpTexture", void 0);
  40141. __decorate([
  40142. BABYLON.serializeAsTexture(),
  40143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40144. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  40145. __decorate([
  40146. BABYLON.serializeAsTexture(),
  40147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40148. ], PBRMaterial.prototype, "refractionTexture", void 0);
  40149. __decorate([
  40150. BABYLON.serializeAsColor3("ambient"),
  40151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40152. ], PBRMaterial.prototype, "ambientColor", void 0);
  40153. __decorate([
  40154. BABYLON.serializeAsColor3("albedo"),
  40155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40156. ], PBRMaterial.prototype, "albedoColor", void 0);
  40157. __decorate([
  40158. BABYLON.serializeAsColor3("reflectivity"),
  40159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40160. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  40161. __decorate([
  40162. BABYLON.serializeAsColor3("reflection"),
  40163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40164. ], PBRMaterial.prototype, "reflectionColor", void 0);
  40165. __decorate([
  40166. BABYLON.serializeAsColor3("emissive"),
  40167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40168. ], PBRMaterial.prototype, "emissiveColor", void 0);
  40169. __decorate([
  40170. BABYLON.serialize(),
  40171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40172. ], PBRMaterial.prototype, "microSurface", void 0);
  40173. __decorate([
  40174. BABYLON.serialize(),
  40175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40176. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  40177. __decorate([
  40178. BABYLON.serialize(),
  40179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40180. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  40181. __decorate([
  40182. BABYLON.serialize(),
  40183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40184. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  40185. __decorate([
  40186. BABYLON.serialize(),
  40187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40188. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40189. __decorate([
  40190. BABYLON.serialize(),
  40191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40192. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40193. __decorate([
  40194. BABYLON.serialize(),
  40195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40196. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  40197. __decorate([
  40198. BABYLON.serialize(),
  40199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40200. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  40201. __decorate([
  40202. BABYLON.serialize(),
  40203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40204. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40205. __decorate([
  40206. BABYLON.serialize(),
  40207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40208. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40209. __decorate([
  40210. BABYLON.serialize(),
  40211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40212. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40213. __decorate([
  40214. BABYLON.serialize(),
  40215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40216. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40217. __decorate([
  40218. BABYLON.serialize(),
  40219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40220. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40221. __decorate([
  40222. BABYLON.serialize(),
  40223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40224. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40225. __decorate([
  40226. BABYLON.serialize(),
  40227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40228. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40229. __decorate([
  40230. BABYLON.serialize(),
  40231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40232. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40233. __decorate([
  40234. BABYLON.serialize(),
  40235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40236. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40237. __decorate([
  40238. BABYLON.serialize(),
  40239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40240. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40241. __decorate([
  40242. BABYLON.serialize(),
  40243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40244. ], PBRMaterial.prototype, "useParallax", void 0);
  40245. __decorate([
  40246. BABYLON.serialize(),
  40247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40248. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40249. __decorate([
  40250. BABYLON.serialize(),
  40251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40252. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40253. __decorate([
  40254. BABYLON.serialize(),
  40255. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40256. ], PBRMaterial.prototype, "disableLighting", void 0);
  40257. __decorate([
  40258. BABYLON.serialize(),
  40259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40260. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40261. __decorate([
  40262. BABYLON.serialize(),
  40263. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40264. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40265. __decorate([
  40266. BABYLON.serialize(),
  40267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40268. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40269. __decorate([
  40270. BABYLON.serialize(),
  40271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40272. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40273. __decorate([
  40274. BABYLON.serialize(),
  40275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40276. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40277. __decorate([
  40278. BABYLON.serialize(),
  40279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40280. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40281. __decorate([
  40282. BABYLON.serialize(),
  40283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40284. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40285. __decorate([
  40286. BABYLON.serializeAsTexture(),
  40287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40288. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40289. __decorate([
  40290. BABYLON.serialize(),
  40291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40292. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40293. __decorate([
  40294. BABYLON.serialize(),
  40295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40296. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40297. __decorate([
  40298. BABYLON.serialize(),
  40299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40300. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40301. return PBRMaterial;
  40302. }(BABYLON.PBRBaseMaterial));
  40303. BABYLON.PBRMaterial = PBRMaterial;
  40304. })(BABYLON || (BABYLON = {}));
  40305. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40306. var BABYLON;
  40307. (function (BABYLON) {
  40308. /**
  40309. * The PBR material of BJS following the metal roughness convention.
  40310. *
  40311. * This fits to the PBR convention in the GLTF definition:
  40312. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40313. */
  40314. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40315. __extends(PBRMetallicRoughnessMaterial, _super);
  40316. /**
  40317. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40318. *
  40319. * @param name The material name
  40320. * @param scene The scene the material will be use in.
  40321. */
  40322. function PBRMetallicRoughnessMaterial(name, scene) {
  40323. var _this = _super.call(this, name, scene) || this;
  40324. _this._useRoughnessFromMetallicTextureAlpha = false;
  40325. _this._useRoughnessFromMetallicTextureGreen = true;
  40326. _this._useMetallnessFromMetallicTextureBlue = true;
  40327. _this._forceMetallicWorkflow = true;
  40328. return _this;
  40329. }
  40330. /**
  40331. * Return the currrent class name of the material.
  40332. */
  40333. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40334. return "PBRMetallicRoughnessMaterial";
  40335. };
  40336. /**
  40337. * Return the active textures of the material.
  40338. */
  40339. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40340. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40341. if (this.baseTexture) {
  40342. activeTextures.push(this.baseTexture);
  40343. }
  40344. if (this.metallicRoughnessTexture) {
  40345. activeTextures.push(this.metallicRoughnessTexture);
  40346. }
  40347. return activeTextures;
  40348. };
  40349. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40350. if (_super.prototype.hasTexture.call(this, texture)) {
  40351. return true;
  40352. }
  40353. if (this.baseTexture === texture) {
  40354. return true;
  40355. }
  40356. if (this.metallicRoughnessTexture === texture) {
  40357. return true;
  40358. }
  40359. return false;
  40360. };
  40361. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40362. var _this = this;
  40363. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40364. clone.id = name;
  40365. clone.name = name;
  40366. return clone;
  40367. };
  40368. /**
  40369. * Serialize the material to a parsable JSON object.
  40370. */
  40371. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40373. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40374. return serializationObject;
  40375. };
  40376. /**
  40377. * Parses a JSON object correponding to the serialize function.
  40378. */
  40379. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40380. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40381. };
  40382. __decorate([
  40383. BABYLON.serializeAsColor3(),
  40384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40385. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40386. __decorate([
  40387. BABYLON.serializeAsTexture(),
  40388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40389. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40390. __decorate([
  40391. BABYLON.serialize(),
  40392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40393. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40394. __decorate([
  40395. BABYLON.serialize(),
  40396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40397. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40398. __decorate([
  40399. BABYLON.serializeAsTexture(),
  40400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40401. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40402. return PBRMetallicRoughnessMaterial;
  40403. }(BABYLON.PBRBaseSimpleMaterial));
  40404. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40405. })(BABYLON || (BABYLON = {}));
  40406. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40407. var BABYLON;
  40408. (function (BABYLON) {
  40409. /**
  40410. * The PBR material of BJS following the specular glossiness convention.
  40411. *
  40412. * This fits to the PBR convention in the GLTF definition:
  40413. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40414. */
  40415. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40416. __extends(PBRSpecularGlossinessMaterial, _super);
  40417. /**
  40418. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40419. *
  40420. * @param name The material name
  40421. * @param scene The scene the material will be use in.
  40422. */
  40423. function PBRSpecularGlossinessMaterial(name, scene) {
  40424. var _this = _super.call(this, name, scene) || this;
  40425. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40426. return _this;
  40427. }
  40428. /**
  40429. * Return the currrent class name of the material.
  40430. */
  40431. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40432. return "PBRSpecularGlossinessMaterial";
  40433. };
  40434. /**
  40435. * Return the active textures of the material.
  40436. */
  40437. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40438. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40439. if (this.diffuseTexture) {
  40440. activeTextures.push(this.diffuseTexture);
  40441. }
  40442. if (this.specularGlossinessTexture) {
  40443. activeTextures.push(this.specularGlossinessTexture);
  40444. }
  40445. return activeTextures;
  40446. };
  40447. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40448. if (_super.prototype.hasTexture.call(this, texture)) {
  40449. return true;
  40450. }
  40451. if (this.diffuseTexture === texture) {
  40452. return true;
  40453. }
  40454. if (this.specularGlossinessTexture === texture) {
  40455. return true;
  40456. }
  40457. return false;
  40458. };
  40459. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40460. var _this = this;
  40461. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40462. clone.id = name;
  40463. clone.name = name;
  40464. return clone;
  40465. };
  40466. /**
  40467. * Serialize the material to a parsable JSON object.
  40468. */
  40469. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40471. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40472. return serializationObject;
  40473. };
  40474. /**
  40475. * Parses a JSON object correponding to the serialize function.
  40476. */
  40477. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40478. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40479. };
  40480. __decorate([
  40481. BABYLON.serializeAsColor3("diffuse"),
  40482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40483. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40484. __decorate([
  40485. BABYLON.serializeAsTexture(),
  40486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40487. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40488. __decorate([
  40489. BABYLON.serializeAsColor3("specular"),
  40490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40491. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40492. __decorate([
  40493. BABYLON.serialize(),
  40494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40495. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40496. __decorate([
  40497. BABYLON.serializeAsTexture(),
  40498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40499. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40500. return PBRSpecularGlossinessMaterial;
  40501. }(BABYLON.PBRBaseSimpleMaterial));
  40502. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40503. })(BABYLON || (BABYLON = {}));
  40504. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40505. var BABYLON;
  40506. (function (BABYLON) {
  40507. BABYLON.CameraInputTypes = {};
  40508. var CameraInputsManager = /** @class */ (function () {
  40509. function CameraInputsManager(camera) {
  40510. this.attached = {};
  40511. this.camera = camera;
  40512. this.checkInputs = function () { };
  40513. }
  40514. /**
  40515. * Add an input method to a camera.
  40516. * builtin inputs example: camera.inputs.addGamepad();
  40517. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40518. * @param input camera input method
  40519. */
  40520. CameraInputsManager.prototype.add = function (input) {
  40521. var type = input.getSimpleName();
  40522. if (this.attached[type]) {
  40523. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40524. return;
  40525. }
  40526. this.attached[type] = input;
  40527. input.camera = this.camera;
  40528. //for checkInputs, we are dynamically creating a function
  40529. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40530. if (input.checkInputs) {
  40531. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40532. }
  40533. if (this.attachedElement) {
  40534. input.attachControl(this.attachedElement);
  40535. }
  40536. };
  40537. /**
  40538. * Remove a specific input method from a camera
  40539. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40540. * @param inputToRemove camera input method
  40541. */
  40542. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40543. for (var cam in this.attached) {
  40544. var input = this.attached[cam];
  40545. if (input === inputToRemove) {
  40546. input.detachControl(this.attachedElement);
  40547. input.camera = null;
  40548. delete this.attached[cam];
  40549. this.rebuildInputCheck();
  40550. }
  40551. }
  40552. };
  40553. CameraInputsManager.prototype.removeByType = function (inputType) {
  40554. for (var cam in this.attached) {
  40555. var input = this.attached[cam];
  40556. if (input.getClassName() === inputType) {
  40557. input.detachControl(this.attachedElement);
  40558. input.camera = null;
  40559. delete this.attached[cam];
  40560. this.rebuildInputCheck();
  40561. }
  40562. }
  40563. };
  40564. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40565. var current = this.checkInputs;
  40566. return function () {
  40567. current();
  40568. fn();
  40569. };
  40570. };
  40571. CameraInputsManager.prototype.attachInput = function (input) {
  40572. if (this.attachedElement) {
  40573. input.attachControl(this.attachedElement, this.noPreventDefault);
  40574. }
  40575. };
  40576. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40577. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40578. if (this.attachedElement) {
  40579. return;
  40580. }
  40581. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40582. this.attachedElement = element;
  40583. this.noPreventDefault = noPreventDefault;
  40584. for (var cam in this.attached) {
  40585. this.attached[cam].attachControl(element, noPreventDefault);
  40586. }
  40587. };
  40588. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40589. if (disconnect === void 0) { disconnect = false; }
  40590. if (this.attachedElement !== element) {
  40591. return;
  40592. }
  40593. for (var cam in this.attached) {
  40594. this.attached[cam].detachControl(element);
  40595. if (disconnect) {
  40596. this.attached[cam].camera = null;
  40597. }
  40598. }
  40599. this.attachedElement = null;
  40600. };
  40601. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40602. this.checkInputs = function () { };
  40603. for (var cam in this.attached) {
  40604. var input = this.attached[cam];
  40605. if (input.checkInputs) {
  40606. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40607. }
  40608. }
  40609. };
  40610. /**
  40611. * Remove all attached input methods from a camera
  40612. */
  40613. CameraInputsManager.prototype.clear = function () {
  40614. if (this.attachedElement) {
  40615. this.detachElement(this.attachedElement, true);
  40616. }
  40617. this.attached = {};
  40618. this.attachedElement = null;
  40619. this.checkInputs = function () { };
  40620. };
  40621. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40622. var inputs = {};
  40623. for (var cam in this.attached) {
  40624. var input = this.attached[cam];
  40625. var res = BABYLON.SerializationHelper.Serialize(input);
  40626. inputs[input.getClassName()] = res;
  40627. }
  40628. serializedCamera.inputsmgr = inputs;
  40629. };
  40630. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40631. var parsedInputs = parsedCamera.inputsmgr;
  40632. if (parsedInputs) {
  40633. this.clear();
  40634. for (var n in parsedInputs) {
  40635. var construct = BABYLON.CameraInputTypes[n];
  40636. if (construct) {
  40637. var parsedinput = parsedInputs[n];
  40638. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40639. this.add(input);
  40640. }
  40641. }
  40642. }
  40643. else {
  40644. //2016-03-08 this part is for managing backward compatibility
  40645. for (var n in this.attached) {
  40646. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40647. if (construct) {
  40648. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40649. this.remove(this.attached[n]);
  40650. this.add(input);
  40651. }
  40652. }
  40653. }
  40654. };
  40655. return CameraInputsManager;
  40656. }());
  40657. BABYLON.CameraInputsManager = CameraInputsManager;
  40658. })(BABYLON || (BABYLON = {}));
  40659. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40660. var BABYLON;
  40661. (function (BABYLON) {
  40662. var TargetCamera = /** @class */ (function (_super) {
  40663. __extends(TargetCamera, _super);
  40664. function TargetCamera(name, position, scene) {
  40665. var _this = _super.call(this, name, position, scene) || this;
  40666. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40667. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40668. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40669. _this.speed = 2.0;
  40670. _this.noRotationConstraint = false;
  40671. _this.lockedTarget = null;
  40672. _this._currentTarget = BABYLON.Vector3.Zero();
  40673. _this._viewMatrix = BABYLON.Matrix.Zero();
  40674. _this._camMatrix = BABYLON.Matrix.Zero();
  40675. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40676. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40677. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40678. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40679. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40680. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40681. _this._tempMatrix = BABYLON.Matrix.Zero();
  40682. return _this;
  40683. }
  40684. TargetCamera.prototype.getFrontPosition = function (distance) {
  40685. this.getWorldMatrix();
  40686. var direction = this.getTarget().subtract(this.position);
  40687. direction.normalize();
  40688. direction.scaleInPlace(distance);
  40689. return this.globalPosition.add(direction);
  40690. };
  40691. TargetCamera.prototype._getLockedTargetPosition = function () {
  40692. if (!this.lockedTarget) {
  40693. return null;
  40694. }
  40695. if (this.lockedTarget.absolutePosition) {
  40696. this.lockedTarget.computeWorldMatrix();
  40697. }
  40698. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40699. };
  40700. TargetCamera.prototype.storeState = function () {
  40701. this._storedPosition = this.position.clone();
  40702. this._storedRotation = this.rotation.clone();
  40703. if (this.rotationQuaternion) {
  40704. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40705. }
  40706. return _super.prototype.storeState.call(this);
  40707. };
  40708. /**
  40709. * Restored camera state. You must call storeState() first
  40710. */
  40711. TargetCamera.prototype._restoreStateValues = function () {
  40712. if (!_super.prototype._restoreStateValues.call(this)) {
  40713. return false;
  40714. }
  40715. this.position = this._storedPosition.clone();
  40716. this.rotation = this._storedRotation.clone();
  40717. if (this.rotationQuaternion) {
  40718. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40719. }
  40720. this.cameraDirection.copyFromFloats(0, 0, 0);
  40721. this.cameraRotation.copyFromFloats(0, 0);
  40722. return true;
  40723. };
  40724. // Cache
  40725. TargetCamera.prototype._initCache = function () {
  40726. _super.prototype._initCache.call(this);
  40727. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40728. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40729. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40730. };
  40731. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40732. if (!ignoreParentClass) {
  40733. _super.prototype._updateCache.call(this);
  40734. }
  40735. var lockedTargetPosition = this._getLockedTargetPosition();
  40736. if (!lockedTargetPosition) {
  40737. this._cache.lockedTarget = null;
  40738. }
  40739. else {
  40740. if (!this._cache.lockedTarget) {
  40741. this._cache.lockedTarget = lockedTargetPosition.clone();
  40742. }
  40743. else {
  40744. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40745. }
  40746. }
  40747. this._cache.rotation.copyFrom(this.rotation);
  40748. if (this.rotationQuaternion)
  40749. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40750. };
  40751. // Synchronized
  40752. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40753. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40754. return false;
  40755. }
  40756. var lockedTargetPosition = this._getLockedTargetPosition();
  40757. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40758. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40759. };
  40760. // Methods
  40761. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40762. var engine = this.getEngine();
  40763. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40764. };
  40765. // Target
  40766. TargetCamera.prototype.setTarget = function (target) {
  40767. this.upVector.normalize();
  40768. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40769. this._camMatrix.invert();
  40770. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40771. var vDir = target.subtract(this.position);
  40772. if (vDir.x >= 0.0) {
  40773. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40774. }
  40775. else {
  40776. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40777. }
  40778. this.rotation.z = 0;
  40779. if (isNaN(this.rotation.x)) {
  40780. this.rotation.x = 0;
  40781. }
  40782. if (isNaN(this.rotation.y)) {
  40783. this.rotation.y = 0;
  40784. }
  40785. if (isNaN(this.rotation.z)) {
  40786. this.rotation.z = 0;
  40787. }
  40788. if (this.rotationQuaternion) {
  40789. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40790. }
  40791. };
  40792. /**
  40793. * Return the current target position of the camera. This value is expressed in local space.
  40794. */
  40795. TargetCamera.prototype.getTarget = function () {
  40796. return this._currentTarget;
  40797. };
  40798. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40799. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40800. };
  40801. TargetCamera.prototype._updatePosition = function () {
  40802. if (this.parent) {
  40803. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40804. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40805. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40806. return;
  40807. }
  40808. this.position.addInPlace(this.cameraDirection);
  40809. };
  40810. TargetCamera.prototype._checkInputs = function () {
  40811. var needToMove = this._decideIfNeedsToMove();
  40812. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40813. // Move
  40814. if (needToMove) {
  40815. this._updatePosition();
  40816. }
  40817. // Rotate
  40818. if (needToRotate) {
  40819. this.rotation.x += this.cameraRotation.x;
  40820. this.rotation.y += this.cameraRotation.y;
  40821. //rotate, if quaternion is set and rotation was used
  40822. if (this.rotationQuaternion) {
  40823. var len = this.rotation.lengthSquared();
  40824. if (len) {
  40825. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40826. }
  40827. }
  40828. if (!this.noRotationConstraint) {
  40829. var limit = (Math.PI / 2) * 0.95;
  40830. if (this.rotation.x > limit)
  40831. this.rotation.x = limit;
  40832. if (this.rotation.x < -limit)
  40833. this.rotation.x = -limit;
  40834. }
  40835. }
  40836. // Inertia
  40837. if (needToMove) {
  40838. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40839. this.cameraDirection.x = 0;
  40840. }
  40841. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40842. this.cameraDirection.y = 0;
  40843. }
  40844. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40845. this.cameraDirection.z = 0;
  40846. }
  40847. this.cameraDirection.scaleInPlace(this.inertia);
  40848. }
  40849. if (needToRotate) {
  40850. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40851. this.cameraRotation.x = 0;
  40852. }
  40853. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40854. this.cameraRotation.y = 0;
  40855. }
  40856. this.cameraRotation.scaleInPlace(this.inertia);
  40857. }
  40858. _super.prototype._checkInputs.call(this);
  40859. };
  40860. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40861. if (this.rotationQuaternion) {
  40862. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40863. }
  40864. else {
  40865. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40866. }
  40867. //update the up vector!
  40868. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40869. };
  40870. TargetCamera.prototype._getViewMatrix = function () {
  40871. if (this.lockedTarget) {
  40872. this.setTarget(this._getLockedTargetPosition());
  40873. }
  40874. // Compute
  40875. this._updateCameraRotationMatrix();
  40876. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40877. // Computing target and final matrix
  40878. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40879. if (this.getScene().useRightHandedSystem) {
  40880. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40881. }
  40882. else {
  40883. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40884. }
  40885. return this._viewMatrix;
  40886. };
  40887. /**
  40888. * @override
  40889. * Override Camera.createRigCamera
  40890. */
  40891. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40892. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40893. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40894. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40895. if (!this.rotationQuaternion) {
  40896. this.rotationQuaternion = new BABYLON.Quaternion();
  40897. }
  40898. rigCamera._cameraRigParams = {};
  40899. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40900. }
  40901. return rigCamera;
  40902. }
  40903. return null;
  40904. };
  40905. /**
  40906. * @override
  40907. * Override Camera._updateRigCameras
  40908. */
  40909. TargetCamera.prototype._updateRigCameras = function () {
  40910. var camLeft = this._rigCameras[0];
  40911. var camRight = this._rigCameras[1];
  40912. switch (this.cameraRigMode) {
  40913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40914. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40917. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40918. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40919. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40920. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40921. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40922. camLeft.setTarget(this.getTarget());
  40923. camRight.setTarget(this.getTarget());
  40924. break;
  40925. case BABYLON.Camera.RIG_MODE_VR:
  40926. if (camLeft.rotationQuaternion) {
  40927. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40928. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40929. }
  40930. else {
  40931. camLeft.rotation.copyFrom(this.rotation);
  40932. camRight.rotation.copyFrom(this.rotation);
  40933. }
  40934. camLeft.position.copyFrom(this.position);
  40935. camRight.position.copyFrom(this.position);
  40936. break;
  40937. }
  40938. _super.prototype._updateRigCameras.call(this);
  40939. };
  40940. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40941. if (!this._rigCamTransformMatrix) {
  40942. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40943. }
  40944. var target = this.getTarget();
  40945. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40946. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40947. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40948. };
  40949. TargetCamera.prototype.getClassName = function () {
  40950. return "TargetCamera";
  40951. };
  40952. __decorate([
  40953. BABYLON.serializeAsVector3()
  40954. ], TargetCamera.prototype, "rotation", void 0);
  40955. __decorate([
  40956. BABYLON.serialize()
  40957. ], TargetCamera.prototype, "speed", void 0);
  40958. __decorate([
  40959. BABYLON.serializeAsMeshReference("lockedTargetId")
  40960. ], TargetCamera.prototype, "lockedTarget", void 0);
  40961. return TargetCamera;
  40962. }(BABYLON.Camera));
  40963. BABYLON.TargetCamera = TargetCamera;
  40964. })(BABYLON || (BABYLON = {}));
  40965. //# sourceMappingURL=babylon.targetCamera.js.map
  40966. var BABYLON;
  40967. (function (BABYLON) {
  40968. var FreeCameraMouseInput = /** @class */ (function () {
  40969. function FreeCameraMouseInput(touchEnabled) {
  40970. if (touchEnabled === void 0) { touchEnabled = true; }
  40971. this.touchEnabled = touchEnabled;
  40972. this.buttons = [0, 1, 2];
  40973. this.angularSensibility = 2000.0;
  40974. this.previousPosition = null;
  40975. }
  40976. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40977. var _this = this;
  40978. var engine = this.camera.getEngine();
  40979. if (!this._pointerInput) {
  40980. this._pointerInput = function (p, s) {
  40981. var evt = p.event;
  40982. if (engine.isInVRExclusivePointerMode) {
  40983. return;
  40984. }
  40985. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40986. return;
  40987. }
  40988. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40989. return;
  40990. }
  40991. var srcElement = (evt.srcElement || evt.target);
  40992. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40993. try {
  40994. srcElement.setPointerCapture(evt.pointerId);
  40995. }
  40996. catch (e) {
  40997. //Nothing to do with the error. Execution will continue.
  40998. }
  40999. _this.previousPosition = {
  41000. x: evt.clientX,
  41001. y: evt.clientY
  41002. };
  41003. if (!noPreventDefault) {
  41004. evt.preventDefault();
  41005. element.focus();
  41006. }
  41007. }
  41008. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41009. try {
  41010. srcElement.releasePointerCapture(evt.pointerId);
  41011. }
  41012. catch (e) {
  41013. //Nothing to do with the error.
  41014. }
  41015. _this.previousPosition = null;
  41016. if (!noPreventDefault) {
  41017. evt.preventDefault();
  41018. }
  41019. }
  41020. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41021. if (!_this.previousPosition || engine.isPointerLock) {
  41022. return;
  41023. }
  41024. var offsetX = evt.clientX - _this.previousPosition.x;
  41025. var offsetY = evt.clientY - _this.previousPosition.y;
  41026. if (_this.camera.getScene().useRightHandedSystem) {
  41027. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41028. }
  41029. else {
  41030. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41031. }
  41032. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41033. _this.previousPosition = {
  41034. x: evt.clientX,
  41035. y: evt.clientY
  41036. };
  41037. if (!noPreventDefault) {
  41038. evt.preventDefault();
  41039. }
  41040. }
  41041. };
  41042. }
  41043. this._onMouseMove = function (evt) {
  41044. if (!engine.isPointerLock) {
  41045. return;
  41046. }
  41047. if (engine.isInVRExclusivePointerMode) {
  41048. return;
  41049. }
  41050. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41051. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41052. if (_this.camera.getScene().useRightHandedSystem) {
  41053. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41054. }
  41055. else {
  41056. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41057. }
  41058. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41059. _this.previousPosition = null;
  41060. if (!noPreventDefault) {
  41061. evt.preventDefault();
  41062. }
  41063. };
  41064. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  41065. element.addEventListener("mousemove", this._onMouseMove, false);
  41066. };
  41067. FreeCameraMouseInput.prototype.detachControl = function (element) {
  41068. if (this._observer && element) {
  41069. this.camera.getScene().onPointerObservable.remove(this._observer);
  41070. if (this._onMouseMove) {
  41071. element.removeEventListener("mousemove", this._onMouseMove);
  41072. }
  41073. this._observer = null;
  41074. this._onMouseMove = null;
  41075. this.previousPosition = null;
  41076. }
  41077. };
  41078. FreeCameraMouseInput.prototype.getClassName = function () {
  41079. return "FreeCameraMouseInput";
  41080. };
  41081. FreeCameraMouseInput.prototype.getSimpleName = function () {
  41082. return "mouse";
  41083. };
  41084. __decorate([
  41085. BABYLON.serialize()
  41086. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  41087. __decorate([
  41088. BABYLON.serialize()
  41089. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  41090. return FreeCameraMouseInput;
  41091. }());
  41092. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  41093. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  41094. })(BABYLON || (BABYLON = {}));
  41095. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  41096. var BABYLON;
  41097. (function (BABYLON) {
  41098. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  41099. function FreeCameraKeyboardMoveInput() {
  41100. this._keys = new Array();
  41101. this.keysUp = [38];
  41102. this.keysDown = [40];
  41103. this.keysLeft = [37];
  41104. this.keysRight = [39];
  41105. }
  41106. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41107. var _this = this;
  41108. if (this._onCanvasBlurObserver) {
  41109. return;
  41110. }
  41111. this._scene = this.camera.getScene();
  41112. this._engine = this._scene.getEngine();
  41113. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41114. _this._keys = [];
  41115. });
  41116. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41117. var evt = info.event;
  41118. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41119. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41120. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41121. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41122. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41123. var index = _this._keys.indexOf(evt.keyCode);
  41124. if (index === -1) {
  41125. _this._keys.push(evt.keyCode);
  41126. }
  41127. if (!noPreventDefault) {
  41128. evt.preventDefault();
  41129. }
  41130. }
  41131. }
  41132. else {
  41133. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41134. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41135. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41136. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41137. var index = _this._keys.indexOf(evt.keyCode);
  41138. if (index >= 0) {
  41139. _this._keys.splice(index, 1);
  41140. }
  41141. if (!noPreventDefault) {
  41142. evt.preventDefault();
  41143. }
  41144. }
  41145. }
  41146. });
  41147. };
  41148. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41149. if (this._scene) {
  41150. if (this._onKeyboardObserver) {
  41151. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41152. }
  41153. if (this._onCanvasBlurObserver) {
  41154. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41155. }
  41156. this._onKeyboardObserver = null;
  41157. this._onCanvasBlurObserver = null;
  41158. }
  41159. this._keys = [];
  41160. };
  41161. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41162. if (this._onKeyboardObserver) {
  41163. var camera = this.camera;
  41164. // Keyboard
  41165. for (var index = 0; index < this._keys.length; index++) {
  41166. var keyCode = this._keys[index];
  41167. var speed = camera._computeLocalCameraSpeed();
  41168. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41169. camera._localDirection.copyFromFloats(-speed, 0, 0);
  41170. }
  41171. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41172. camera._localDirection.copyFromFloats(0, 0, speed);
  41173. }
  41174. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41175. camera._localDirection.copyFromFloats(speed, 0, 0);
  41176. }
  41177. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41178. camera._localDirection.copyFromFloats(0, 0, -speed);
  41179. }
  41180. if (camera.getScene().useRightHandedSystem) {
  41181. camera._localDirection.z *= -1;
  41182. }
  41183. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  41184. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  41185. camera.cameraDirection.addInPlace(camera._transformedDirection);
  41186. }
  41187. }
  41188. };
  41189. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  41190. return "FreeCameraKeyboardMoveInput";
  41191. };
  41192. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  41193. this._keys = [];
  41194. };
  41195. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41196. return "keyboard";
  41197. };
  41198. __decorate([
  41199. BABYLON.serialize()
  41200. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41201. __decorate([
  41202. BABYLON.serialize()
  41203. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41204. __decorate([
  41205. BABYLON.serialize()
  41206. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41207. __decorate([
  41208. BABYLON.serialize()
  41209. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41210. return FreeCameraKeyboardMoveInput;
  41211. }());
  41212. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  41213. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  41214. })(BABYLON || (BABYLON = {}));
  41215. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  41216. var BABYLON;
  41217. (function (BABYLON) {
  41218. var FreeCameraInputsManager = /** @class */ (function (_super) {
  41219. __extends(FreeCameraInputsManager, _super);
  41220. function FreeCameraInputsManager(camera) {
  41221. return _super.call(this, camera) || this;
  41222. }
  41223. FreeCameraInputsManager.prototype.addKeyboard = function () {
  41224. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  41225. return this;
  41226. };
  41227. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  41228. if (touchEnabled === void 0) { touchEnabled = true; }
  41229. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  41230. return this;
  41231. };
  41232. FreeCameraInputsManager.prototype.addGamepad = function () {
  41233. this.add(new BABYLON.FreeCameraGamepadInput());
  41234. return this;
  41235. };
  41236. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  41237. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  41238. return this;
  41239. };
  41240. FreeCameraInputsManager.prototype.addTouch = function () {
  41241. this.add(new BABYLON.FreeCameraTouchInput());
  41242. return this;
  41243. };
  41244. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  41245. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  41246. return this;
  41247. };
  41248. return FreeCameraInputsManager;
  41249. }(BABYLON.CameraInputsManager));
  41250. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  41251. })(BABYLON || (BABYLON = {}));
  41252. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  41253. var BABYLON;
  41254. (function (BABYLON) {
  41255. var FreeCamera = /** @class */ (function (_super) {
  41256. __extends(FreeCamera, _super);
  41257. function FreeCamera(name, position, scene) {
  41258. var _this = _super.call(this, name, position, scene) || this;
  41259. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41260. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41261. _this.checkCollisions = false;
  41262. _this.applyGravity = false;
  41263. _this._needMoveForGravity = false;
  41264. _this._oldPosition = BABYLON.Vector3.Zero();
  41265. _this._diffPosition = BABYLON.Vector3.Zero();
  41266. _this._newPosition = BABYLON.Vector3.Zero();
  41267. // Collisions
  41268. _this._collisionMask = -1;
  41269. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41270. if (collidedMesh === void 0) { collidedMesh = null; }
  41271. //TODO move this to the collision coordinator!
  41272. if (_this.getScene().workerCollisions)
  41273. newPosition.multiplyInPlace(_this._collider._radius);
  41274. var updatePosition = function (newPos) {
  41275. _this._newPosition.copyFrom(newPos);
  41276. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41277. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41278. _this.position.addInPlace(_this._diffPosition);
  41279. if (_this.onCollide && collidedMesh) {
  41280. _this.onCollide(collidedMesh);
  41281. }
  41282. }
  41283. };
  41284. updatePosition(newPosition);
  41285. };
  41286. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41287. _this.inputs.addKeyboard().addMouse();
  41288. return _this;
  41289. }
  41290. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41291. //-- begin properties for backward compatibility for inputs
  41292. /**
  41293. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41294. * Higher values reduce sensitivity.
  41295. */
  41296. get: function () {
  41297. var mouse = this.inputs.attached["mouse"];
  41298. if (mouse)
  41299. return mouse.angularSensibility;
  41300. return 0;
  41301. },
  41302. /**
  41303. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41304. * Higher values reduce sensitivity.
  41305. */
  41306. set: function (value) {
  41307. var mouse = this.inputs.attached["mouse"];
  41308. if (mouse)
  41309. mouse.angularSensibility = value;
  41310. },
  41311. enumerable: true,
  41312. configurable: true
  41313. });
  41314. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41315. get: function () {
  41316. var keyboard = this.inputs.attached["keyboard"];
  41317. if (keyboard)
  41318. return keyboard.keysUp;
  41319. return [];
  41320. },
  41321. set: function (value) {
  41322. var keyboard = this.inputs.attached["keyboard"];
  41323. if (keyboard)
  41324. keyboard.keysUp = value;
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41330. get: function () {
  41331. var keyboard = this.inputs.attached["keyboard"];
  41332. if (keyboard)
  41333. return keyboard.keysDown;
  41334. return [];
  41335. },
  41336. set: function (value) {
  41337. var keyboard = this.inputs.attached["keyboard"];
  41338. if (keyboard)
  41339. keyboard.keysDown = value;
  41340. },
  41341. enumerable: true,
  41342. configurable: true
  41343. });
  41344. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41345. get: function () {
  41346. var keyboard = this.inputs.attached["keyboard"];
  41347. if (keyboard)
  41348. return keyboard.keysLeft;
  41349. return [];
  41350. },
  41351. set: function (value) {
  41352. var keyboard = this.inputs.attached["keyboard"];
  41353. if (keyboard)
  41354. keyboard.keysLeft = value;
  41355. },
  41356. enumerable: true,
  41357. configurable: true
  41358. });
  41359. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41360. get: function () {
  41361. var keyboard = this.inputs.attached["keyboard"];
  41362. if (keyboard)
  41363. return keyboard.keysRight;
  41364. return [];
  41365. },
  41366. set: function (value) {
  41367. var keyboard = this.inputs.attached["keyboard"];
  41368. if (keyboard)
  41369. keyboard.keysRight = value;
  41370. },
  41371. enumerable: true,
  41372. configurable: true
  41373. });
  41374. // Controls
  41375. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41376. this.inputs.attachElement(element, noPreventDefault);
  41377. };
  41378. FreeCamera.prototype.detachControl = function (element) {
  41379. this.inputs.detachElement(element);
  41380. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41381. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41382. };
  41383. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41384. get: function () {
  41385. return this._collisionMask;
  41386. },
  41387. set: function (mask) {
  41388. this._collisionMask = !isNaN(mask) ? mask : -1;
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41394. var globalPosition;
  41395. if (this.parent) {
  41396. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41397. }
  41398. else {
  41399. globalPosition = this.position;
  41400. }
  41401. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41402. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41403. if (!this._collider) {
  41404. this._collider = new BABYLON.Collider();
  41405. }
  41406. this._collider._radius = this.ellipsoid;
  41407. this._collider.collisionMask = this._collisionMask;
  41408. //no need for clone, as long as gravity is not on.
  41409. var actualDisplacement = displacement;
  41410. //add gravity to the direction to prevent the dual-collision checking
  41411. if (this.applyGravity) {
  41412. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41413. actualDisplacement = displacement.add(this.getScene().gravity);
  41414. }
  41415. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41416. };
  41417. FreeCamera.prototype._checkInputs = function () {
  41418. if (!this._localDirection) {
  41419. this._localDirection = BABYLON.Vector3.Zero();
  41420. this._transformedDirection = BABYLON.Vector3.Zero();
  41421. }
  41422. this.inputs.checkInputs();
  41423. _super.prototype._checkInputs.call(this);
  41424. };
  41425. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41426. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41427. };
  41428. FreeCamera.prototype._updatePosition = function () {
  41429. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41430. this._collideWithWorld(this.cameraDirection);
  41431. }
  41432. else {
  41433. _super.prototype._updatePosition.call(this);
  41434. }
  41435. };
  41436. FreeCamera.prototype.dispose = function () {
  41437. this.inputs.clear();
  41438. _super.prototype.dispose.call(this);
  41439. };
  41440. FreeCamera.prototype.getClassName = function () {
  41441. return "FreeCamera";
  41442. };
  41443. __decorate([
  41444. BABYLON.serializeAsVector3()
  41445. ], FreeCamera.prototype, "ellipsoid", void 0);
  41446. __decorate([
  41447. BABYLON.serializeAsVector3()
  41448. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41449. __decorate([
  41450. BABYLON.serialize()
  41451. ], FreeCamera.prototype, "checkCollisions", void 0);
  41452. __decorate([
  41453. BABYLON.serialize()
  41454. ], FreeCamera.prototype, "applyGravity", void 0);
  41455. return FreeCamera;
  41456. }(BABYLON.TargetCamera));
  41457. BABYLON.FreeCamera = FreeCamera;
  41458. })(BABYLON || (BABYLON = {}));
  41459. //# sourceMappingURL=babylon.freeCamera.js.map
  41460. var BABYLON;
  41461. (function (BABYLON) {
  41462. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41463. function ArcRotateCameraKeyboardMoveInput() {
  41464. this._keys = new Array();
  41465. this.keysUp = [38];
  41466. this.keysDown = [40];
  41467. this.keysLeft = [37];
  41468. this.keysRight = [39];
  41469. this.keysReset = [220];
  41470. this.panningSensibility = 50.0;
  41471. this.zoomingSensibility = 25.0;
  41472. this.useAltToZoom = true;
  41473. }
  41474. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41475. var _this = this;
  41476. if (this._onCanvasBlurObserver) {
  41477. return;
  41478. }
  41479. this._scene = this.camera.getScene();
  41480. this._engine = this._scene.getEngine();
  41481. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41482. _this._keys = [];
  41483. });
  41484. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41485. var evt = info.event;
  41486. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41487. _this._ctrlPressed = evt.ctrlKey;
  41488. _this._altPressed = evt.altKey;
  41489. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41490. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41491. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41492. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41493. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41494. var index = _this._keys.indexOf(evt.keyCode);
  41495. if (index === -1) {
  41496. _this._keys.push(evt.keyCode);
  41497. }
  41498. if (evt.preventDefault) {
  41499. if (!noPreventDefault) {
  41500. evt.preventDefault();
  41501. }
  41502. }
  41503. }
  41504. }
  41505. else {
  41506. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41507. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41508. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41509. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41510. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41511. var index = _this._keys.indexOf(evt.keyCode);
  41512. if (index >= 0) {
  41513. _this._keys.splice(index, 1);
  41514. }
  41515. if (evt.preventDefault) {
  41516. if (!noPreventDefault) {
  41517. evt.preventDefault();
  41518. }
  41519. }
  41520. }
  41521. }
  41522. });
  41523. };
  41524. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41525. if (this._scene) {
  41526. if (this._onKeyboardObserver) {
  41527. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41528. }
  41529. if (this._onCanvasBlurObserver) {
  41530. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41531. }
  41532. this._onKeyboardObserver = null;
  41533. this._onCanvasBlurObserver = null;
  41534. }
  41535. this._keys = [];
  41536. };
  41537. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41538. if (this._onKeyboardObserver) {
  41539. var camera = this.camera;
  41540. for (var index = 0; index < this._keys.length; index++) {
  41541. var keyCode = this._keys[index];
  41542. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41543. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41544. camera.inertialPanningX -= 1 / this.panningSensibility;
  41545. }
  41546. else {
  41547. camera.inertialAlphaOffset -= 0.01;
  41548. }
  41549. }
  41550. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41551. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41552. camera.inertialPanningY += 1 / this.panningSensibility;
  41553. }
  41554. else if (this._altPressed && this.useAltToZoom) {
  41555. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41556. }
  41557. else {
  41558. camera.inertialBetaOffset -= 0.01;
  41559. }
  41560. }
  41561. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41562. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41563. camera.inertialPanningX += 1 / this.panningSensibility;
  41564. }
  41565. else {
  41566. camera.inertialAlphaOffset += 0.01;
  41567. }
  41568. }
  41569. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41570. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41571. camera.inertialPanningY -= 1 / this.panningSensibility;
  41572. }
  41573. else if (this._altPressed && this.useAltToZoom) {
  41574. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41575. }
  41576. else {
  41577. camera.inertialBetaOffset += 0.01;
  41578. }
  41579. }
  41580. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41581. camera.restoreState();
  41582. }
  41583. }
  41584. }
  41585. };
  41586. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41587. return "ArcRotateCameraKeyboardMoveInput";
  41588. };
  41589. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41590. return "keyboard";
  41591. };
  41592. __decorate([
  41593. BABYLON.serialize()
  41594. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41595. __decorate([
  41596. BABYLON.serialize()
  41597. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41598. __decorate([
  41599. BABYLON.serialize()
  41600. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41601. __decorate([
  41602. BABYLON.serialize()
  41603. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41604. __decorate([
  41605. BABYLON.serialize()
  41606. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41607. __decorate([
  41608. BABYLON.serialize()
  41609. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41610. __decorate([
  41611. BABYLON.serialize()
  41612. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41613. __decorate([
  41614. BABYLON.serialize()
  41615. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41616. return ArcRotateCameraKeyboardMoveInput;
  41617. }());
  41618. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41619. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41620. })(BABYLON || (BABYLON = {}));
  41621. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41622. var BABYLON;
  41623. (function (BABYLON) {
  41624. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41625. function ArcRotateCameraMouseWheelInput() {
  41626. this.wheelPrecision = 3.0;
  41627. /**
  41628. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41629. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41630. */
  41631. this.wheelDeltaPercentage = 0;
  41632. }
  41633. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41634. var _this = this;
  41635. this._wheel = function (p, s) {
  41636. //sanity check - this should be a PointerWheel event.
  41637. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41638. return;
  41639. var event = p.event;
  41640. var delta = 0;
  41641. if (event.wheelDelta) {
  41642. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41643. }
  41644. else if (event.detail) {
  41645. delta = -event.detail / _this.wheelPrecision;
  41646. }
  41647. if (delta)
  41648. _this.camera.inertialRadiusOffset += delta;
  41649. if (event.preventDefault) {
  41650. if (!noPreventDefault) {
  41651. event.preventDefault();
  41652. }
  41653. }
  41654. };
  41655. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41656. };
  41657. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41658. if (this._observer && element) {
  41659. this.camera.getScene().onPointerObservable.remove(this._observer);
  41660. this._observer = null;
  41661. this._wheel = null;
  41662. }
  41663. };
  41664. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41665. return "ArcRotateCameraMouseWheelInput";
  41666. };
  41667. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41668. return "mousewheel";
  41669. };
  41670. __decorate([
  41671. BABYLON.serialize()
  41672. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41673. __decorate([
  41674. BABYLON.serialize()
  41675. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41676. return ArcRotateCameraMouseWheelInput;
  41677. }());
  41678. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41679. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41680. })(BABYLON || (BABYLON = {}));
  41681. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41682. var BABYLON;
  41683. (function (BABYLON) {
  41684. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41685. function ArcRotateCameraPointersInput() {
  41686. this.buttons = [0, 1, 2];
  41687. this.angularSensibilityX = 1000.0;
  41688. this.angularSensibilityY = 1000.0;
  41689. this.pinchPrecision = 12.0;
  41690. /**
  41691. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41692. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41693. */
  41694. this.pinchDeltaPercentage = 0;
  41695. this.panningSensibility = 1000.0;
  41696. this.multiTouchPanning = true;
  41697. this.multiTouchPanAndZoom = true;
  41698. this._isPanClick = false;
  41699. this.pinchInwards = true;
  41700. }
  41701. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41702. var _this = this;
  41703. var engine = this.camera.getEngine();
  41704. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41705. var pointA = null;
  41706. var pointB = null;
  41707. var previousPinchSquaredDistance = 0;
  41708. var initialDistance = 0;
  41709. var twoFingerActivityCount = 0;
  41710. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41711. this._pointerInput = function (p, s) {
  41712. var evt = p.event;
  41713. var isTouch = p.event.pointerType === "touch";
  41714. if (engine.isInVRExclusivePointerMode) {
  41715. return;
  41716. }
  41717. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41718. return;
  41719. }
  41720. var srcElement = (evt.srcElement || evt.target);
  41721. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41722. try {
  41723. srcElement.setPointerCapture(evt.pointerId);
  41724. }
  41725. catch (e) {
  41726. //Nothing to do with the error. Execution will continue.
  41727. }
  41728. // Manage panning with pan button click
  41729. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41730. // manage pointers
  41731. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41732. if (pointA === null) {
  41733. pointA = cacheSoloPointer;
  41734. }
  41735. else if (pointB === null) {
  41736. pointB = cacheSoloPointer;
  41737. }
  41738. if (!noPreventDefault) {
  41739. evt.preventDefault();
  41740. element.focus();
  41741. }
  41742. }
  41743. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41744. _this.camera.restoreState();
  41745. }
  41746. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41747. try {
  41748. srcElement.releasePointerCapture(evt.pointerId);
  41749. }
  41750. catch (e) {
  41751. //Nothing to do with the error.
  41752. }
  41753. cacheSoloPointer = null;
  41754. previousPinchSquaredDistance = 0;
  41755. previousMultiTouchPanPosition.isPaning = false;
  41756. previousMultiTouchPanPosition.isPinching = false;
  41757. twoFingerActivityCount = 0;
  41758. initialDistance = 0;
  41759. if (!isTouch) {
  41760. pointB = null; // Mouse and pen are mono pointer
  41761. }
  41762. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41763. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41764. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41765. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41766. if (engine.badOS) {
  41767. pointA = pointB = null;
  41768. }
  41769. else {
  41770. //only remove the impacted pointer in case of multitouch allowing on most
  41771. //platforms switching from rotate to zoom and pan seamlessly.
  41772. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41773. pointA = pointB;
  41774. pointB = null;
  41775. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41776. }
  41777. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41778. pointB = null;
  41779. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41780. }
  41781. else {
  41782. pointA = pointB = null;
  41783. }
  41784. }
  41785. if (!noPreventDefault) {
  41786. evt.preventDefault();
  41787. }
  41788. }
  41789. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41790. if (!noPreventDefault) {
  41791. evt.preventDefault();
  41792. }
  41793. // One button down
  41794. if (pointA && pointB === null && cacheSoloPointer) {
  41795. if (_this.panningSensibility !== 0 &&
  41796. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41797. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41798. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41799. }
  41800. else {
  41801. var offsetX = evt.clientX - cacheSoloPointer.x;
  41802. var offsetY = evt.clientY - cacheSoloPointer.y;
  41803. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41804. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41805. }
  41806. cacheSoloPointer.x = evt.clientX;
  41807. cacheSoloPointer.y = evt.clientY;
  41808. }
  41809. else if (pointA && pointB) {
  41810. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41811. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41812. ed.x = evt.clientX;
  41813. ed.y = evt.clientY;
  41814. var direction = _this.pinchInwards ? 1 : -1;
  41815. var distX = pointA.x - pointB.x;
  41816. var distY = pointA.y - pointB.y;
  41817. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41818. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41819. if (previousPinchSquaredDistance === 0) {
  41820. initialDistance = pinchDistance;
  41821. previousPinchSquaredDistance = pinchSquaredDistance;
  41822. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41823. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41824. return;
  41825. }
  41826. if (_this.multiTouchPanAndZoom) {
  41827. if (_this.pinchDeltaPercentage) {
  41828. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41829. }
  41830. else {
  41831. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41832. (_this.pinchPrecision *
  41833. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41834. direction);
  41835. }
  41836. if (_this.panningSensibility !== 0) {
  41837. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41838. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41839. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41840. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41841. previousMultiTouchPanPosition.x = pointersCenterX;
  41842. previousMultiTouchPanPosition.y = pointersCenterY;
  41843. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41844. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41845. }
  41846. }
  41847. else {
  41848. twoFingerActivityCount++;
  41849. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41850. if (_this.pinchDeltaPercentage) {
  41851. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41852. }
  41853. else {
  41854. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41855. (_this.pinchPrecision *
  41856. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41857. direction);
  41858. }
  41859. previousMultiTouchPanPosition.isPaning = false;
  41860. previousMultiTouchPanPosition.isPinching = true;
  41861. }
  41862. else {
  41863. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41864. if (!previousMultiTouchPanPosition.isPaning) {
  41865. previousMultiTouchPanPosition.isPaning = true;
  41866. previousMultiTouchPanPosition.isPinching = false;
  41867. previousMultiTouchPanPosition.x = ed.x;
  41868. previousMultiTouchPanPosition.y = ed.y;
  41869. return;
  41870. }
  41871. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41872. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41873. }
  41874. }
  41875. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41876. previousMultiTouchPanPosition.x = ed.x;
  41877. previousMultiTouchPanPosition.y = ed.y;
  41878. }
  41879. }
  41880. previousPinchSquaredDistance = pinchSquaredDistance;
  41881. }
  41882. }
  41883. };
  41884. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41885. this._onContextMenu = function (evt) {
  41886. evt.preventDefault();
  41887. };
  41888. if (!this.camera._useCtrlForPanning) {
  41889. element.addEventListener("contextmenu", this._onContextMenu, false);
  41890. }
  41891. this._onLostFocus = function () {
  41892. //this._keys = [];
  41893. pointA = pointB = null;
  41894. previousPinchSquaredDistance = 0;
  41895. previousMultiTouchPanPosition.isPaning = false;
  41896. previousMultiTouchPanPosition.isPinching = false;
  41897. twoFingerActivityCount = 0;
  41898. cacheSoloPointer = null;
  41899. initialDistance = 0;
  41900. };
  41901. this._onMouseMove = function (evt) {
  41902. if (!engine.isPointerLock) {
  41903. return;
  41904. }
  41905. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41906. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41907. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41908. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41909. if (!noPreventDefault) {
  41910. evt.preventDefault();
  41911. }
  41912. };
  41913. this._onGestureStart = function (e) {
  41914. if (window.MSGesture === undefined) {
  41915. return;
  41916. }
  41917. if (!_this._MSGestureHandler) {
  41918. _this._MSGestureHandler = new MSGesture();
  41919. _this._MSGestureHandler.target = element;
  41920. }
  41921. _this._MSGestureHandler.addPointer(e.pointerId);
  41922. };
  41923. this._onGesture = function (e) {
  41924. _this.camera.radius *= e.scale;
  41925. if (e.preventDefault) {
  41926. if (!noPreventDefault) {
  41927. e.stopPropagation();
  41928. e.preventDefault();
  41929. }
  41930. }
  41931. };
  41932. element.addEventListener("mousemove", this._onMouseMove, false);
  41933. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41934. element.addEventListener("MSGestureChange", this._onGesture, false);
  41935. BABYLON.Tools.RegisterTopRootEvents([
  41936. { name: "blur", handler: this._onLostFocus }
  41937. ]);
  41938. };
  41939. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41940. if (this._onLostFocus) {
  41941. BABYLON.Tools.UnregisterTopRootEvents([
  41942. { name: "blur", handler: this._onLostFocus }
  41943. ]);
  41944. }
  41945. if (element && this._observer) {
  41946. this.camera.getScene().onPointerObservable.remove(this._observer);
  41947. this._observer = null;
  41948. if (this._onContextMenu) {
  41949. element.removeEventListener("contextmenu", this._onContextMenu);
  41950. }
  41951. if (this._onMouseMove) {
  41952. element.removeEventListener("mousemove", this._onMouseMove);
  41953. }
  41954. if (this._onGestureStart) {
  41955. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41956. }
  41957. if (this._onGesture) {
  41958. element.removeEventListener("MSGestureChange", this._onGesture);
  41959. }
  41960. this._isPanClick = false;
  41961. this.pinchInwards = true;
  41962. this._onMouseMove = null;
  41963. this._onGestureStart = null;
  41964. this._onGesture = null;
  41965. this._MSGestureHandler = null;
  41966. this._onLostFocus = null;
  41967. this._onContextMenu = null;
  41968. }
  41969. };
  41970. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41971. return "ArcRotateCameraPointersInput";
  41972. };
  41973. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41974. return "pointers";
  41975. };
  41976. __decorate([
  41977. BABYLON.serialize()
  41978. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41979. __decorate([
  41980. BABYLON.serialize()
  41981. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41982. __decorate([
  41983. BABYLON.serialize()
  41984. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41985. __decorate([
  41986. BABYLON.serialize()
  41987. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41988. __decorate([
  41989. BABYLON.serialize()
  41990. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41991. __decorate([
  41992. BABYLON.serialize()
  41993. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41994. __decorate([
  41995. BABYLON.serialize()
  41996. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41997. __decorate([
  41998. BABYLON.serialize()
  41999. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  42000. return ArcRotateCameraPointersInput;
  42001. }());
  42002. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  42003. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  42004. })(BABYLON || (BABYLON = {}));
  42005. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  42006. var BABYLON;
  42007. (function (BABYLON) {
  42008. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  42009. __extends(ArcRotateCameraInputsManager, _super);
  42010. function ArcRotateCameraInputsManager(camera) {
  42011. return _super.call(this, camera) || this;
  42012. }
  42013. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  42014. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  42015. return this;
  42016. };
  42017. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  42018. this.add(new BABYLON.ArcRotateCameraPointersInput());
  42019. return this;
  42020. };
  42021. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  42022. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  42023. return this;
  42024. };
  42025. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  42026. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  42027. return this;
  42028. };
  42029. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  42030. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  42031. return this;
  42032. };
  42033. return ArcRotateCameraInputsManager;
  42034. }(BABYLON.CameraInputsManager));
  42035. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  42036. })(BABYLON || (BABYLON = {}));
  42037. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  42038. var BABYLON;
  42039. (function (BABYLON) {
  42040. var ArcRotateCamera = /** @class */ (function (_super) {
  42041. __extends(ArcRotateCamera, _super);
  42042. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  42043. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  42044. _this.inertialAlphaOffset = 0;
  42045. _this.inertialBetaOffset = 0;
  42046. _this.inertialRadiusOffset = 0;
  42047. _this.lowerAlphaLimit = null;
  42048. _this.upperAlphaLimit = null;
  42049. _this.lowerBetaLimit = 0.01;
  42050. _this.upperBetaLimit = Math.PI;
  42051. _this.lowerRadiusLimit = null;
  42052. _this.upperRadiusLimit = null;
  42053. _this.inertialPanningX = 0;
  42054. _this.inertialPanningY = 0;
  42055. _this.pinchToPanMaxDistance = 20;
  42056. _this.panningDistanceLimit = null;
  42057. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  42058. _this.panningInertia = 0.9;
  42059. //-- end properties for backward compatibility for inputs
  42060. _this.zoomOnFactor = 1;
  42061. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  42062. _this.allowUpsideDown = true;
  42063. _this._viewMatrix = new BABYLON.Matrix();
  42064. // Panning
  42065. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  42066. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  42067. _this.checkCollisions = false;
  42068. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42069. _this._previousPosition = BABYLON.Vector3.Zero();
  42070. _this._collisionVelocity = BABYLON.Vector3.Zero();
  42071. _this._newPosition = BABYLON.Vector3.Zero();
  42072. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42073. if (collidedMesh === void 0) { collidedMesh = null; }
  42074. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  42075. newPosition.multiplyInPlace(_this._collider._radius);
  42076. }
  42077. if (!collidedMesh) {
  42078. _this._previousPosition.copyFrom(_this.position);
  42079. }
  42080. else {
  42081. _this.setPosition(newPosition);
  42082. if (_this.onCollide) {
  42083. _this.onCollide(collidedMesh);
  42084. }
  42085. }
  42086. // Recompute because of constraints
  42087. var cosa = Math.cos(_this.alpha);
  42088. var sina = Math.sin(_this.alpha);
  42089. var cosb = Math.cos(_this.beta);
  42090. var sinb = Math.sin(_this.beta);
  42091. if (sinb === 0) {
  42092. sinb = 0.0001;
  42093. }
  42094. var target = _this._getTargetPosition();
  42095. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  42096. _this.position.copyFrom(_this._newPosition);
  42097. var up = _this.upVector;
  42098. if (_this.allowUpsideDown && _this.beta < 0) {
  42099. up = up.clone();
  42100. up = up.negate();
  42101. }
  42102. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  42103. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  42104. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  42105. _this._collisionTriggered = false;
  42106. };
  42107. _this._target = BABYLON.Vector3.Zero();
  42108. if (target) {
  42109. _this.setTarget(target);
  42110. }
  42111. _this.alpha = alpha;
  42112. _this.beta = beta;
  42113. _this.radius = radius;
  42114. _this.getViewMatrix();
  42115. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  42116. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  42117. return _this;
  42118. }
  42119. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  42120. get: function () {
  42121. return this._target;
  42122. },
  42123. set: function (value) {
  42124. this.setTarget(value);
  42125. },
  42126. enumerable: true,
  42127. configurable: true
  42128. });
  42129. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  42130. //-- begin properties for backward compatibility for inputs
  42131. get: function () {
  42132. var pointers = this.inputs.attached["pointers"];
  42133. if (pointers)
  42134. return pointers.angularSensibilityX;
  42135. return 0;
  42136. },
  42137. set: function (value) {
  42138. var pointers = this.inputs.attached["pointers"];
  42139. if (pointers) {
  42140. pointers.angularSensibilityX = value;
  42141. }
  42142. },
  42143. enumerable: true,
  42144. configurable: true
  42145. });
  42146. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  42147. get: function () {
  42148. var pointers = this.inputs.attached["pointers"];
  42149. if (pointers)
  42150. return pointers.angularSensibilityY;
  42151. return 0;
  42152. },
  42153. set: function (value) {
  42154. var pointers = this.inputs.attached["pointers"];
  42155. if (pointers) {
  42156. pointers.angularSensibilityY = value;
  42157. }
  42158. },
  42159. enumerable: true,
  42160. configurable: true
  42161. });
  42162. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  42163. get: function () {
  42164. var pointers = this.inputs.attached["pointers"];
  42165. if (pointers)
  42166. return pointers.pinchPrecision;
  42167. return 0;
  42168. },
  42169. set: function (value) {
  42170. var pointers = this.inputs.attached["pointers"];
  42171. if (pointers) {
  42172. pointers.pinchPrecision = value;
  42173. }
  42174. },
  42175. enumerable: true,
  42176. configurable: true
  42177. });
  42178. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  42179. get: function () {
  42180. var pointers = this.inputs.attached["pointers"];
  42181. if (pointers)
  42182. return pointers.pinchDeltaPercentage;
  42183. return 0;
  42184. },
  42185. set: function (value) {
  42186. var pointers = this.inputs.attached["pointers"];
  42187. if (pointers) {
  42188. pointers.pinchDeltaPercentage = value;
  42189. }
  42190. },
  42191. enumerable: true,
  42192. configurable: true
  42193. });
  42194. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  42195. get: function () {
  42196. var pointers = this.inputs.attached["pointers"];
  42197. if (pointers)
  42198. return pointers.panningSensibility;
  42199. return 0;
  42200. },
  42201. set: function (value) {
  42202. var pointers = this.inputs.attached["pointers"];
  42203. if (pointers) {
  42204. pointers.panningSensibility = value;
  42205. }
  42206. },
  42207. enumerable: true,
  42208. configurable: true
  42209. });
  42210. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  42211. get: function () {
  42212. var keyboard = this.inputs.attached["keyboard"];
  42213. if (keyboard)
  42214. return keyboard.keysUp;
  42215. return [];
  42216. },
  42217. set: function (value) {
  42218. var keyboard = this.inputs.attached["keyboard"];
  42219. if (keyboard)
  42220. keyboard.keysUp = value;
  42221. },
  42222. enumerable: true,
  42223. configurable: true
  42224. });
  42225. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  42226. get: function () {
  42227. var keyboard = this.inputs.attached["keyboard"];
  42228. if (keyboard)
  42229. return keyboard.keysDown;
  42230. return [];
  42231. },
  42232. set: function (value) {
  42233. var keyboard = this.inputs.attached["keyboard"];
  42234. if (keyboard)
  42235. keyboard.keysDown = value;
  42236. },
  42237. enumerable: true,
  42238. configurable: true
  42239. });
  42240. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  42241. get: function () {
  42242. var keyboard = this.inputs.attached["keyboard"];
  42243. if (keyboard)
  42244. return keyboard.keysLeft;
  42245. return [];
  42246. },
  42247. set: function (value) {
  42248. var keyboard = this.inputs.attached["keyboard"];
  42249. if (keyboard)
  42250. keyboard.keysLeft = value;
  42251. },
  42252. enumerable: true,
  42253. configurable: true
  42254. });
  42255. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  42256. get: function () {
  42257. var keyboard = this.inputs.attached["keyboard"];
  42258. if (keyboard)
  42259. return keyboard.keysRight;
  42260. return [];
  42261. },
  42262. set: function (value) {
  42263. var keyboard = this.inputs.attached["keyboard"];
  42264. if (keyboard)
  42265. keyboard.keysRight = value;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42271. get: function () {
  42272. var mousewheel = this.inputs.attached["mousewheel"];
  42273. if (mousewheel)
  42274. return mousewheel.wheelPrecision;
  42275. return 0;
  42276. },
  42277. set: function (value) {
  42278. var mousewheel = this.inputs.attached["mousewheel"];
  42279. if (mousewheel)
  42280. mousewheel.wheelPrecision = value;
  42281. },
  42282. enumerable: true,
  42283. configurable: true
  42284. });
  42285. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42286. get: function () {
  42287. var mousewheel = this.inputs.attached["mousewheel"];
  42288. if (mousewheel)
  42289. return mousewheel.wheelDeltaPercentage;
  42290. return 0;
  42291. },
  42292. set: function (value) {
  42293. var mousewheel = this.inputs.attached["mousewheel"];
  42294. if (mousewheel)
  42295. mousewheel.wheelDeltaPercentage = value;
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42301. get: function () {
  42302. return this._bouncingBehavior;
  42303. },
  42304. enumerable: true,
  42305. configurable: true
  42306. });
  42307. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42308. get: function () {
  42309. return this._bouncingBehavior != null;
  42310. },
  42311. set: function (value) {
  42312. if (value === this.useBouncingBehavior) {
  42313. return;
  42314. }
  42315. if (value) {
  42316. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42317. this.addBehavior(this._bouncingBehavior);
  42318. }
  42319. else if (this._bouncingBehavior) {
  42320. this.removeBehavior(this._bouncingBehavior);
  42321. this._bouncingBehavior = null;
  42322. }
  42323. },
  42324. enumerable: true,
  42325. configurable: true
  42326. });
  42327. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42328. get: function () {
  42329. return this._framingBehavior;
  42330. },
  42331. enumerable: true,
  42332. configurable: true
  42333. });
  42334. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42335. get: function () {
  42336. return this._framingBehavior != null;
  42337. },
  42338. set: function (value) {
  42339. if (value === this.useFramingBehavior) {
  42340. return;
  42341. }
  42342. if (value) {
  42343. this._framingBehavior = new BABYLON.FramingBehavior();
  42344. this.addBehavior(this._framingBehavior);
  42345. }
  42346. else if (this._framingBehavior) {
  42347. this.removeBehavior(this._framingBehavior);
  42348. this._framingBehavior = null;
  42349. }
  42350. },
  42351. enumerable: true,
  42352. configurable: true
  42353. });
  42354. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42355. get: function () {
  42356. return this._autoRotationBehavior;
  42357. },
  42358. enumerable: true,
  42359. configurable: true
  42360. });
  42361. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42362. get: function () {
  42363. return this._autoRotationBehavior != null;
  42364. },
  42365. set: function (value) {
  42366. if (value === this.useAutoRotationBehavior) {
  42367. return;
  42368. }
  42369. if (value) {
  42370. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42371. this.addBehavior(this._autoRotationBehavior);
  42372. }
  42373. else if (this._autoRotationBehavior) {
  42374. this.removeBehavior(this._autoRotationBehavior);
  42375. this._autoRotationBehavior = null;
  42376. }
  42377. },
  42378. enumerable: true,
  42379. configurable: true
  42380. });
  42381. // Cache
  42382. ArcRotateCamera.prototype._initCache = function () {
  42383. _super.prototype._initCache.call(this);
  42384. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42385. this._cache.alpha = undefined;
  42386. this._cache.beta = undefined;
  42387. this._cache.radius = undefined;
  42388. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42389. };
  42390. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42391. if (!ignoreParentClass) {
  42392. _super.prototype._updateCache.call(this);
  42393. }
  42394. this._cache._target.copyFrom(this._getTargetPosition());
  42395. this._cache.alpha = this.alpha;
  42396. this._cache.beta = this.beta;
  42397. this._cache.radius = this.radius;
  42398. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42399. };
  42400. ArcRotateCamera.prototype._getTargetPosition = function () {
  42401. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42402. var pos = this._targetHost.getAbsolutePosition();
  42403. if (this._targetBoundingCenter) {
  42404. pos.addToRef(this._targetBoundingCenter, this._target);
  42405. }
  42406. else {
  42407. this._target.copyFrom(pos);
  42408. }
  42409. }
  42410. var lockedTargetPosition = this._getLockedTargetPosition();
  42411. if (lockedTargetPosition) {
  42412. return lockedTargetPosition;
  42413. }
  42414. return this._target;
  42415. };
  42416. ArcRotateCamera.prototype.storeState = function () {
  42417. this._storedAlpha = this.alpha;
  42418. this._storedBeta = this.beta;
  42419. this._storedRadius = this.radius;
  42420. this._storedTarget = this._getTargetPosition().clone();
  42421. return _super.prototype.storeState.call(this);
  42422. };
  42423. /**
  42424. * Restored camera state. You must call storeState() first
  42425. */
  42426. ArcRotateCamera.prototype._restoreStateValues = function () {
  42427. if (!_super.prototype._restoreStateValues.call(this)) {
  42428. return false;
  42429. }
  42430. this.alpha = this._storedAlpha;
  42431. this.beta = this._storedBeta;
  42432. this.radius = this._storedRadius;
  42433. this.setTarget(this._storedTarget.clone());
  42434. this.inertialAlphaOffset = 0;
  42435. this.inertialBetaOffset = 0;
  42436. this.inertialRadiusOffset = 0;
  42437. this.inertialPanningX = 0;
  42438. this.inertialPanningY = 0;
  42439. return true;
  42440. };
  42441. // Synchronized
  42442. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42443. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42444. return false;
  42445. return this._cache._target.equals(this._getTargetPosition())
  42446. && this._cache.alpha === this.alpha
  42447. && this._cache.beta === this.beta
  42448. && this._cache.radius === this.radius
  42449. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42450. };
  42451. // Methods
  42452. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42453. var _this = this;
  42454. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42455. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42456. this._useCtrlForPanning = useCtrlForPanning;
  42457. this._panningMouseButton = panningMouseButton;
  42458. this.inputs.attachElement(element, noPreventDefault);
  42459. this._reset = function () {
  42460. _this.inertialAlphaOffset = 0;
  42461. _this.inertialBetaOffset = 0;
  42462. _this.inertialRadiusOffset = 0;
  42463. _this.inertialPanningX = 0;
  42464. _this.inertialPanningY = 0;
  42465. };
  42466. };
  42467. ArcRotateCamera.prototype.detachControl = function (element) {
  42468. this.inputs.detachElement(element);
  42469. if (this._reset) {
  42470. this._reset();
  42471. }
  42472. };
  42473. ArcRotateCamera.prototype._checkInputs = function () {
  42474. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42475. if (this._collisionTriggered) {
  42476. return;
  42477. }
  42478. this.inputs.checkInputs();
  42479. // Inertia
  42480. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42481. if (this.getScene().useRightHandedSystem) {
  42482. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42483. }
  42484. else {
  42485. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42486. }
  42487. this.beta += this.inertialBetaOffset;
  42488. this.radius -= this.inertialRadiusOffset;
  42489. this.inertialAlphaOffset *= this.inertia;
  42490. this.inertialBetaOffset *= this.inertia;
  42491. this.inertialRadiusOffset *= this.inertia;
  42492. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42493. this.inertialAlphaOffset = 0;
  42494. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42495. this.inertialBetaOffset = 0;
  42496. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42497. this.inertialRadiusOffset = 0;
  42498. }
  42499. // Panning inertia
  42500. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42501. if (!this._localDirection) {
  42502. this._localDirection = BABYLON.Vector3.Zero();
  42503. this._transformedDirection = BABYLON.Vector3.Zero();
  42504. }
  42505. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42506. this._localDirection.multiplyInPlace(this.panningAxis);
  42507. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42508. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42509. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42510. if (!this.panningAxis.y) {
  42511. this._transformedDirection.y = 0;
  42512. }
  42513. if (!this._targetHost) {
  42514. if (this.panningDistanceLimit) {
  42515. this._transformedDirection.addInPlace(this._target);
  42516. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42517. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42518. this._target.copyFrom(this._transformedDirection);
  42519. }
  42520. }
  42521. else {
  42522. this._target.addInPlace(this._transformedDirection);
  42523. }
  42524. }
  42525. this.inertialPanningX *= this.panningInertia;
  42526. this.inertialPanningY *= this.panningInertia;
  42527. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42528. this.inertialPanningX = 0;
  42529. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42530. this.inertialPanningY = 0;
  42531. }
  42532. // Limits
  42533. this._checkLimits();
  42534. _super.prototype._checkInputs.call(this);
  42535. };
  42536. ArcRotateCamera.prototype._checkLimits = function () {
  42537. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42538. if (this.allowUpsideDown && this.beta > Math.PI) {
  42539. this.beta = this.beta - (2 * Math.PI);
  42540. }
  42541. }
  42542. else {
  42543. if (this.beta < this.lowerBetaLimit) {
  42544. this.beta = this.lowerBetaLimit;
  42545. }
  42546. }
  42547. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42548. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42549. this.beta = this.beta + (2 * Math.PI);
  42550. }
  42551. }
  42552. else {
  42553. if (this.beta > this.upperBetaLimit) {
  42554. this.beta = this.upperBetaLimit;
  42555. }
  42556. }
  42557. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42558. this.alpha = this.lowerAlphaLimit;
  42559. }
  42560. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42561. this.alpha = this.upperAlphaLimit;
  42562. }
  42563. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42564. this.radius = this.lowerRadiusLimit;
  42565. }
  42566. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42567. this.radius = this.upperRadiusLimit;
  42568. }
  42569. };
  42570. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42571. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42572. this.radius = radiusv3.length();
  42573. if (this.radius === 0) {
  42574. this.radius = 0.0001; // Just to avoid division by zero
  42575. }
  42576. // Alpha
  42577. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42578. if (radiusv3.z < 0) {
  42579. this.alpha = 2 * Math.PI - this.alpha;
  42580. }
  42581. // Beta
  42582. this.beta = Math.acos(radiusv3.y / this.radius);
  42583. this._checkLimits();
  42584. };
  42585. ArcRotateCamera.prototype.setPosition = function (position) {
  42586. if (this.position.equals(position)) {
  42587. return;
  42588. }
  42589. this.position.copyFrom(position);
  42590. this.rebuildAnglesAndRadius();
  42591. };
  42592. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42593. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42594. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42595. if (target.getBoundingInfo) {
  42596. if (toBoundingCenter) {
  42597. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42598. }
  42599. else {
  42600. this._targetBoundingCenter = null;
  42601. }
  42602. this._targetHost = target;
  42603. this._target = this._getTargetPosition();
  42604. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42605. }
  42606. else {
  42607. var newTarget = target;
  42608. var currentTarget = this._getTargetPosition();
  42609. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42610. return;
  42611. }
  42612. this._targetHost = null;
  42613. this._target = newTarget;
  42614. this._targetBoundingCenter = null;
  42615. this.onMeshTargetChangedObservable.notifyObservers(null);
  42616. }
  42617. this.rebuildAnglesAndRadius();
  42618. };
  42619. ArcRotateCamera.prototype._getViewMatrix = function () {
  42620. // Compute
  42621. var cosa = Math.cos(this.alpha);
  42622. var sina = Math.sin(this.alpha);
  42623. var cosb = Math.cos(this.beta);
  42624. var sinb = Math.sin(this.beta);
  42625. if (sinb === 0) {
  42626. sinb = 0.0001;
  42627. }
  42628. var target = this._getTargetPosition();
  42629. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42630. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42631. if (!this._collider) {
  42632. this._collider = new BABYLON.Collider();
  42633. }
  42634. this._collider._radius = this.collisionRadius;
  42635. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42636. this._collisionTriggered = true;
  42637. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42638. }
  42639. else {
  42640. this.position.copyFrom(this._newPosition);
  42641. var up = this.upVector;
  42642. if (this.allowUpsideDown && sinb < 0) {
  42643. up = up.clone();
  42644. up = up.negate();
  42645. }
  42646. if (this.getScene().useRightHandedSystem) {
  42647. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42648. }
  42649. else {
  42650. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42651. }
  42652. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42653. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42654. }
  42655. this._currentTarget = target;
  42656. return this._viewMatrix;
  42657. };
  42658. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42659. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42660. meshes = meshes || this.getScene().meshes;
  42661. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42662. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42663. this.radius = distance * this.zoomOnFactor;
  42664. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42665. };
  42666. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42667. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42668. var meshesOrMinMaxVector;
  42669. var distance;
  42670. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42671. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42672. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42673. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42674. }
  42675. else {
  42676. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42677. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42678. distance = minMaxVectorAndDistance.distance;
  42679. }
  42680. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42681. if (!doNotUpdateMaxZ) {
  42682. this.maxZ = distance * 2;
  42683. }
  42684. };
  42685. /**
  42686. * @override
  42687. * Override Camera.createRigCamera
  42688. */
  42689. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42690. var alphaShift = 0;
  42691. switch (this.cameraRigMode) {
  42692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42694. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42695. case BABYLON.Camera.RIG_MODE_VR:
  42696. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42697. break;
  42698. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42699. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42700. break;
  42701. }
  42702. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42703. rigCam._cameraRigParams = {};
  42704. return rigCam;
  42705. };
  42706. /**
  42707. * @override
  42708. * Override Camera._updateRigCameras
  42709. */
  42710. ArcRotateCamera.prototype._updateRigCameras = function () {
  42711. var camLeft = this._rigCameras[0];
  42712. var camRight = this._rigCameras[1];
  42713. camLeft.beta = camRight.beta = this.beta;
  42714. camLeft.radius = camRight.radius = this.radius;
  42715. switch (this.cameraRigMode) {
  42716. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42719. case BABYLON.Camera.RIG_MODE_VR:
  42720. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42721. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42722. break;
  42723. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42724. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42725. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42726. break;
  42727. }
  42728. _super.prototype._updateRigCameras.call(this);
  42729. };
  42730. ArcRotateCamera.prototype.dispose = function () {
  42731. this.inputs.clear();
  42732. _super.prototype.dispose.call(this);
  42733. };
  42734. ArcRotateCamera.prototype.getClassName = function () {
  42735. return "ArcRotateCamera";
  42736. };
  42737. __decorate([
  42738. BABYLON.serialize()
  42739. ], ArcRotateCamera.prototype, "alpha", void 0);
  42740. __decorate([
  42741. BABYLON.serialize()
  42742. ], ArcRotateCamera.prototype, "beta", void 0);
  42743. __decorate([
  42744. BABYLON.serialize()
  42745. ], ArcRotateCamera.prototype, "radius", void 0);
  42746. __decorate([
  42747. BABYLON.serializeAsVector3("target")
  42748. ], ArcRotateCamera.prototype, "_target", void 0);
  42749. __decorate([
  42750. BABYLON.serialize()
  42751. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42752. __decorate([
  42753. BABYLON.serialize()
  42754. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42755. __decorate([
  42756. BABYLON.serialize()
  42757. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42758. __decorate([
  42759. BABYLON.serialize()
  42760. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42761. __decorate([
  42762. BABYLON.serialize()
  42763. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42764. __decorate([
  42765. BABYLON.serialize()
  42766. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42767. __decorate([
  42768. BABYLON.serialize()
  42769. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42770. __decorate([
  42771. BABYLON.serialize()
  42772. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42773. __decorate([
  42774. BABYLON.serialize()
  42775. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42776. __decorate([
  42777. BABYLON.serialize()
  42778. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42779. __decorate([
  42780. BABYLON.serialize()
  42781. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42782. __decorate([
  42783. BABYLON.serialize()
  42784. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42785. __decorate([
  42786. BABYLON.serialize()
  42787. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42788. __decorate([
  42789. BABYLON.serializeAsVector3()
  42790. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42791. __decorate([
  42792. BABYLON.serialize()
  42793. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42794. __decorate([
  42795. BABYLON.serialize()
  42796. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42797. __decorate([
  42798. BABYLON.serialize()
  42799. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42800. return ArcRotateCamera;
  42801. }(BABYLON.TargetCamera));
  42802. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42803. })(BABYLON || (BABYLON = {}));
  42804. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42805. var BABYLON;
  42806. (function (BABYLON) {
  42807. /**
  42808. * The HemisphericLight simulates the ambient environment light,
  42809. * so the passed direction is the light reflection direction, not the incoming direction.
  42810. */
  42811. var HemisphericLight = /** @class */ (function (_super) {
  42812. __extends(HemisphericLight, _super);
  42813. /**
  42814. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42815. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42816. * The HemisphericLight can't cast shadows.
  42817. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42818. * @param name The friendly name of the light
  42819. * @param direction The direction of the light reflection
  42820. * @param scene The scene the light belongs to
  42821. */
  42822. function HemisphericLight(name, direction, scene) {
  42823. var _this = _super.call(this, name, scene) || this;
  42824. /**
  42825. * The groundColor is the light in the opposite direction to the one specified during creation.
  42826. * 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.
  42827. */
  42828. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42829. _this.direction = direction || BABYLON.Vector3.Up();
  42830. return _this;
  42831. }
  42832. HemisphericLight.prototype._buildUniformLayout = function () {
  42833. this._uniformBuffer.addUniform("vLightData", 4);
  42834. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42835. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42836. this._uniformBuffer.addUniform("vLightGround", 3);
  42837. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42838. this._uniformBuffer.addUniform("depthValues", 2);
  42839. this._uniformBuffer.create();
  42840. };
  42841. /**
  42842. * Returns the string "HemisphericLight".
  42843. * @return The class name
  42844. */
  42845. HemisphericLight.prototype.getClassName = function () {
  42846. return "HemisphericLight";
  42847. };
  42848. /**
  42849. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42850. * Returns the updated direction.
  42851. * @param target The target the direction should point to
  42852. * @return The computed direction
  42853. */
  42854. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42855. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42856. return this.direction;
  42857. };
  42858. /**
  42859. * Returns the shadow generator associated to the light.
  42860. * @returns Always null for hemispheric lights because it does not support shadows.
  42861. */
  42862. HemisphericLight.prototype.getShadowGenerator = function () {
  42863. return null;
  42864. };
  42865. /**
  42866. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42867. * @param effect The effect to update
  42868. * @param lightIndex The index of the light in the effect to update
  42869. * @returns The hemispheric light
  42870. */
  42871. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42872. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42873. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42874. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42875. return this;
  42876. };
  42877. /**
  42878. * @ignore internal use only.
  42879. */
  42880. HemisphericLight.prototype._getWorldMatrix = function () {
  42881. if (!this._worldMatrix) {
  42882. this._worldMatrix = BABYLON.Matrix.Identity();
  42883. }
  42884. return this._worldMatrix;
  42885. };
  42886. /**
  42887. * Returns the integer 3.
  42888. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  42889. */
  42890. HemisphericLight.prototype.getTypeID = function () {
  42891. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42892. };
  42893. __decorate([
  42894. BABYLON.serializeAsColor3()
  42895. ], HemisphericLight.prototype, "groundColor", void 0);
  42896. __decorate([
  42897. BABYLON.serializeAsVector3()
  42898. ], HemisphericLight.prototype, "direction", void 0);
  42899. return HemisphericLight;
  42900. }(BABYLON.Light));
  42901. BABYLON.HemisphericLight = HemisphericLight;
  42902. })(BABYLON || (BABYLON = {}));
  42903. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42904. var BABYLON;
  42905. (function (BABYLON) {
  42906. /**
  42907. * Base implementation of @see IShadowLight
  42908. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  42909. */
  42910. var ShadowLight = /** @class */ (function (_super) {
  42911. __extends(ShadowLight, _super);
  42912. function ShadowLight() {
  42913. var _this = _super !== null && _super.apply(this, arguments) || this;
  42914. _this._needProjectionMatrixCompute = true;
  42915. return _this;
  42916. }
  42917. Object.defineProperty(ShadowLight.prototype, "direction", {
  42918. get: function () {
  42919. return this._direction;
  42920. },
  42921. /**
  42922. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  42923. */
  42924. set: function (value) {
  42925. this._direction = value;
  42926. },
  42927. enumerable: true,
  42928. configurable: true
  42929. });
  42930. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42931. /**
  42932. * Gets the shadow projection clipping minimum z value.
  42933. */
  42934. get: function () {
  42935. return this._shadowMinZ;
  42936. },
  42937. /**
  42938. * Sets the shadow projection clipping minimum z value.
  42939. */
  42940. set: function (value) {
  42941. this._shadowMinZ = value;
  42942. this.forceProjectionMatrixCompute();
  42943. },
  42944. enumerable: true,
  42945. configurable: true
  42946. });
  42947. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42948. /**
  42949. * Sets the shadow projection clipping maximum z value.
  42950. */
  42951. get: function () {
  42952. return this._shadowMaxZ;
  42953. },
  42954. /**
  42955. * Gets the shadow projection clipping maximum z value.
  42956. */
  42957. set: function (value) {
  42958. this._shadowMaxZ = value;
  42959. this.forceProjectionMatrixCompute();
  42960. },
  42961. enumerable: true,
  42962. configurable: true
  42963. });
  42964. /**
  42965. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  42966. * @returns true if the information has been computed, false if it does not need to (no parenting)
  42967. */
  42968. ShadowLight.prototype.computeTransformedInformation = function () {
  42969. if (this.parent && this.parent.getWorldMatrix) {
  42970. if (!this.transformedPosition) {
  42971. this.transformedPosition = BABYLON.Vector3.Zero();
  42972. }
  42973. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42974. // In case the direction is present.
  42975. if (this.direction) {
  42976. if (!this.transformedDirection) {
  42977. this.transformedDirection = BABYLON.Vector3.Zero();
  42978. }
  42979. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42980. }
  42981. return true;
  42982. }
  42983. return false;
  42984. };
  42985. /**
  42986. * Return the depth scale used for the shadow map.
  42987. * @returns the depth scale.
  42988. */
  42989. ShadowLight.prototype.getDepthScale = function () {
  42990. return 50.0;
  42991. };
  42992. /**
  42993. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  42994. * @param faceIndex The index of the face we are computed the direction to generate shadow
  42995. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  42996. */
  42997. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42998. return this.transformedDirection ? this.transformedDirection : this.direction;
  42999. };
  43000. /**
  43001. * Returns the ShadowLight absolute position in the World.
  43002. * @returns the position vector in world space
  43003. */
  43004. ShadowLight.prototype.getAbsolutePosition = function () {
  43005. return this.transformedPosition ? this.transformedPosition : this.position;
  43006. };
  43007. /**
  43008. * Sets the ShadowLight direction toward the passed target.
  43009. * @param target The point tot target in local space
  43010. * @returns the updated ShadowLight direction
  43011. */
  43012. ShadowLight.prototype.setDirectionToTarget = function (target) {
  43013. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  43014. return this.direction;
  43015. };
  43016. /**
  43017. * Returns the light rotation in euler definition.
  43018. * @returns the x y z rotation in local space.
  43019. */
  43020. ShadowLight.prototype.getRotation = function () {
  43021. this.direction.normalize();
  43022. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  43023. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  43024. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  43025. };
  43026. /**
  43027. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  43028. * @returns true if a cube texture needs to be use
  43029. */
  43030. ShadowLight.prototype.needCube = function () {
  43031. return false;
  43032. };
  43033. /**
  43034. * Detects if the projection matrix requires to be recomputed this frame.
  43035. * @returns true if it requires to be recomputed otherwise, false.
  43036. */
  43037. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  43038. return this._needProjectionMatrixCompute;
  43039. };
  43040. /**
  43041. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  43042. */
  43043. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  43044. this._needProjectionMatrixCompute = true;
  43045. };
  43046. /**
  43047. * Get the world matrix of the sahdow lights.
  43048. * @ignore Internal Use Only
  43049. */
  43050. ShadowLight.prototype._getWorldMatrix = function () {
  43051. if (!this._worldMatrix) {
  43052. this._worldMatrix = BABYLON.Matrix.Identity();
  43053. }
  43054. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  43055. return this._worldMatrix;
  43056. };
  43057. /**
  43058. * Gets the minZ used for shadow according to both the scene and the light.
  43059. * @param activeCamera The camera we are returning the min for
  43060. * @returns the depth min z
  43061. */
  43062. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  43063. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  43064. };
  43065. /**
  43066. * Gets the maxZ used for shadow according to both the scene and the light.
  43067. * @param activeCamera The camera we are returning the max for
  43068. * @returns the depth max z
  43069. */
  43070. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  43071. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  43072. };
  43073. /**
  43074. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  43075. * @param matrix The materix to updated with the projection information
  43076. * @param viewMatrix The transform matrix of the light
  43077. * @param renderList The list of mesh to render in the map
  43078. * @returns The current light
  43079. */
  43080. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43081. if (this.customProjectionMatrixBuilder) {
  43082. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  43083. }
  43084. else {
  43085. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43086. }
  43087. return this;
  43088. };
  43089. __decorate([
  43090. BABYLON.serializeAsVector3()
  43091. ], ShadowLight.prototype, "position", void 0);
  43092. __decorate([
  43093. BABYLON.serializeAsVector3()
  43094. /**
  43095. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  43096. */
  43097. ], ShadowLight.prototype, "direction", null);
  43098. __decorate([
  43099. BABYLON.serialize()
  43100. ], ShadowLight.prototype, "shadowMinZ", null);
  43101. __decorate([
  43102. BABYLON.serialize()
  43103. ], ShadowLight.prototype, "shadowMaxZ", null);
  43104. return ShadowLight;
  43105. }(BABYLON.Light));
  43106. BABYLON.ShadowLight = ShadowLight;
  43107. })(BABYLON || (BABYLON = {}));
  43108. //# sourceMappingURL=babylon.shadowLight.js.map
  43109. var BABYLON;
  43110. (function (BABYLON) {
  43111. /**
  43112. * A point light is a light defined by an unique point in world space.
  43113. * The light is emitted in every direction from this point.
  43114. * A good example of a point light is a standard light bulb.
  43115. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43116. */
  43117. var PointLight = /** @class */ (function (_super) {
  43118. __extends(PointLight, _super);
  43119. /**
  43120. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  43121. * A PointLight emits the light in every direction.
  43122. * It can cast shadows.
  43123. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  43124. * ```javascript
  43125. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  43126. * ```
  43127. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43128. * @param name The light friendly name
  43129. * @param position The position of the point light in the scene
  43130. * @param scene The scene the lights belongs to
  43131. */
  43132. function PointLight(name, position, scene) {
  43133. var _this = _super.call(this, name, scene) || this;
  43134. _this._shadowAngle = Math.PI / 2;
  43135. _this.position = position;
  43136. return _this;
  43137. }
  43138. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  43139. /**
  43140. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43141. * This specifies what angle the shadow will use to be created.
  43142. *
  43143. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43144. */
  43145. get: function () {
  43146. return this._shadowAngle;
  43147. },
  43148. /**
  43149. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43150. * This specifies what angle the shadow will use to be created.
  43151. *
  43152. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43153. */
  43154. set: function (value) {
  43155. this._shadowAngle = value;
  43156. this.forceProjectionMatrixCompute();
  43157. },
  43158. enumerable: true,
  43159. configurable: true
  43160. });
  43161. Object.defineProperty(PointLight.prototype, "direction", {
  43162. /**
  43163. * Gets the direction if it has been set.
  43164. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43165. */
  43166. get: function () {
  43167. return this._direction;
  43168. },
  43169. /**
  43170. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43171. */
  43172. set: function (value) {
  43173. var previousNeedCube = this.needCube();
  43174. this._direction = value;
  43175. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  43176. this._shadowGenerator.recreateShadowMap();
  43177. }
  43178. },
  43179. enumerable: true,
  43180. configurable: true
  43181. });
  43182. /**
  43183. * Returns the string "PointLight"
  43184. * @returns the class name
  43185. */
  43186. PointLight.prototype.getClassName = function () {
  43187. return "PointLight";
  43188. };
  43189. /**
  43190. * Returns the integer 0.
  43191. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43192. */
  43193. PointLight.prototype.getTypeID = function () {
  43194. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  43195. };
  43196. /**
  43197. * Specifies wether or not the shadowmap should be a cube texture.
  43198. * @returns true if the shadowmap needs to be a cube texture.
  43199. */
  43200. PointLight.prototype.needCube = function () {
  43201. return !this.direction;
  43202. };
  43203. /**
  43204. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  43205. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43206. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43207. */
  43208. PointLight.prototype.getShadowDirection = function (faceIndex) {
  43209. if (this.direction) {
  43210. return _super.prototype.getShadowDirection.call(this, faceIndex);
  43211. }
  43212. else {
  43213. switch (faceIndex) {
  43214. case 0:
  43215. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  43216. case 1:
  43217. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  43218. case 2:
  43219. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  43220. case 3:
  43221. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  43222. case 4:
  43223. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  43224. case 5:
  43225. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  43226. }
  43227. }
  43228. return BABYLON.Vector3.Zero();
  43229. };
  43230. /**
  43231. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  43232. * - fov = PI / 2
  43233. * - aspect ratio : 1.0
  43234. * - z-near and far equal to the active camera minZ and maxZ.
  43235. * Returns the PointLight.
  43236. */
  43237. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43238. var activeCamera = this.getScene().activeCamera;
  43239. if (!activeCamera) {
  43240. return;
  43241. }
  43242. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43243. };
  43244. PointLight.prototype._buildUniformLayout = function () {
  43245. this._uniformBuffer.addUniform("vLightData", 4);
  43246. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43247. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43248. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43249. this._uniformBuffer.addUniform("depthValues", 2);
  43250. this._uniformBuffer.create();
  43251. };
  43252. /**
  43253. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  43254. * @param effect The effect to update
  43255. * @param lightIndex The index of the light in the effect to update
  43256. * @returns The point light
  43257. */
  43258. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  43259. if (this.computeTransformedInformation()) {
  43260. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  43261. return this;
  43262. }
  43263. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  43264. return this;
  43265. };
  43266. __decorate([
  43267. BABYLON.serialize()
  43268. ], PointLight.prototype, "shadowAngle", null);
  43269. return PointLight;
  43270. }(BABYLON.ShadowLight));
  43271. BABYLON.PointLight = PointLight;
  43272. })(BABYLON || (BABYLON = {}));
  43273. //# sourceMappingURL=babylon.pointLight.js.map
  43274. var BABYLON;
  43275. (function (BABYLON) {
  43276. /**
  43277. * A directional light is defined by a direction (what a surprise!).
  43278. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  43279. * 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.
  43280. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43281. */
  43282. var DirectionalLight = /** @class */ (function (_super) {
  43283. __extends(DirectionalLight, _super);
  43284. /**
  43285. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  43286. * The directional light is emitted from everywhere in the given direction.
  43287. * It can cast shawdows.
  43288. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43289. * @param name The friendly name of the light
  43290. * @param direction The direction of the light
  43291. * @param scene The scene the light belongs to
  43292. */
  43293. function DirectionalLight(name, direction, scene) {
  43294. var _this = _super.call(this, name, scene) || this;
  43295. _this._shadowFrustumSize = 0;
  43296. _this._shadowOrthoScale = 0.5;
  43297. /**
  43298. * Automatically compute the projection matrix to best fit (including all the casters)
  43299. * on each frame.
  43300. */
  43301. _this.autoUpdateExtends = true;
  43302. // Cache
  43303. _this._orthoLeft = Number.MAX_VALUE;
  43304. _this._orthoRight = Number.MIN_VALUE;
  43305. _this._orthoTop = Number.MIN_VALUE;
  43306. _this._orthoBottom = Number.MAX_VALUE;
  43307. _this.position = direction.scale(-1.0);
  43308. _this.direction = direction;
  43309. return _this;
  43310. }
  43311. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  43312. /**
  43313. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  43314. */
  43315. get: function () {
  43316. return this._shadowFrustumSize;
  43317. },
  43318. /**
  43319. * Specifies a fix frustum size for the shadow generation.
  43320. */
  43321. set: function (value) {
  43322. this._shadowFrustumSize = value;
  43323. this.forceProjectionMatrixCompute();
  43324. },
  43325. enumerable: true,
  43326. configurable: true
  43327. });
  43328. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  43329. /**
  43330. * Gets the shadow projection scale against the optimal computed one.
  43331. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43332. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43333. */
  43334. get: function () {
  43335. return this._shadowOrthoScale;
  43336. },
  43337. /**
  43338. * Sets the shadow projection scale against the optimal computed one.
  43339. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43340. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43341. */
  43342. set: function (value) {
  43343. this._shadowOrthoScale = value;
  43344. this.forceProjectionMatrixCompute();
  43345. },
  43346. enumerable: true,
  43347. configurable: true
  43348. });
  43349. /**
  43350. * Returns the string "DirectionalLight".
  43351. * @return The class name
  43352. */
  43353. DirectionalLight.prototype.getClassName = function () {
  43354. return "DirectionalLight";
  43355. };
  43356. /**
  43357. * Returns the integer 1.
  43358. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43359. */
  43360. DirectionalLight.prototype.getTypeID = function () {
  43361. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  43362. };
  43363. /**
  43364. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  43365. * Returns the DirectionalLight Shadow projection matrix.
  43366. */
  43367. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43368. if (this.shadowFrustumSize > 0) {
  43369. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43370. }
  43371. else {
  43372. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43373. }
  43374. };
  43375. /**
  43376. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43377. * Returns the DirectionalLight Shadow projection matrix.
  43378. */
  43379. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43380. var activeCamera = this.getScene().activeCamera;
  43381. if (!activeCamera) {
  43382. return;
  43383. }
  43384. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43385. };
  43386. /**
  43387. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43388. * Returns the DirectionalLight Shadow projection matrix.
  43389. */
  43390. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43391. var activeCamera = this.getScene().activeCamera;
  43392. if (!activeCamera) {
  43393. return;
  43394. }
  43395. // Check extends
  43396. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43397. var tempVector3 = BABYLON.Vector3.Zero();
  43398. this._orthoLeft = Number.MAX_VALUE;
  43399. this._orthoRight = Number.MIN_VALUE;
  43400. this._orthoTop = Number.MIN_VALUE;
  43401. this._orthoBottom = Number.MAX_VALUE;
  43402. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43403. var mesh = renderList[meshIndex];
  43404. if (!mesh) {
  43405. continue;
  43406. }
  43407. var boundingInfo = mesh.getBoundingInfo();
  43408. var boundingBox = boundingInfo.boundingBox;
  43409. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43410. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43411. if (tempVector3.x < this._orthoLeft)
  43412. this._orthoLeft = tempVector3.x;
  43413. if (tempVector3.y < this._orthoBottom)
  43414. this._orthoBottom = tempVector3.y;
  43415. if (tempVector3.x > this._orthoRight)
  43416. this._orthoRight = tempVector3.x;
  43417. if (tempVector3.y > this._orthoTop)
  43418. this._orthoTop = tempVector3.y;
  43419. }
  43420. }
  43421. }
  43422. var xOffset = this._orthoRight - this._orthoLeft;
  43423. var yOffset = this._orthoTop - this._orthoBottom;
  43424. 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);
  43425. };
  43426. DirectionalLight.prototype._buildUniformLayout = function () {
  43427. this._uniformBuffer.addUniform("vLightData", 4);
  43428. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43429. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43430. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43431. this._uniformBuffer.addUniform("depthValues", 2);
  43432. this._uniformBuffer.create();
  43433. };
  43434. /**
  43435. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43436. * @param effect The effect to update
  43437. * @param lightIndex The index of the light in the effect to update
  43438. * @returns The directional light
  43439. */
  43440. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43441. if (this.computeTransformedInformation()) {
  43442. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43443. return this;
  43444. }
  43445. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43446. return this;
  43447. };
  43448. /**
  43449. * Gets the minZ used for shadow according to both the scene and the light.
  43450. *
  43451. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43452. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43453. * @param activeCamera The camera we are returning the min for
  43454. * @returns the depth min z
  43455. */
  43456. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43457. return 1;
  43458. };
  43459. /**
  43460. * Gets the maxZ used for shadow according to both the scene and the light.
  43461. *
  43462. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43463. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43464. * @param activeCamera The camera we are returning the max for
  43465. * @returns the depth max z
  43466. */
  43467. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43468. return 1;
  43469. };
  43470. __decorate([
  43471. BABYLON.serialize()
  43472. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43473. __decorate([
  43474. BABYLON.serialize()
  43475. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43476. __decorate([
  43477. BABYLON.serialize()
  43478. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43479. return DirectionalLight;
  43480. }(BABYLON.ShadowLight));
  43481. BABYLON.DirectionalLight = DirectionalLight;
  43482. })(BABYLON || (BABYLON = {}));
  43483. //# sourceMappingURL=babylon.directionalLight.js.map
  43484. var BABYLON;
  43485. (function (BABYLON) {
  43486. /**
  43487. * A spot light is defined by a position, a direction, an angle, and an exponent.
  43488. * These values define a cone of light starting from the position, emitting toward the direction.
  43489. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  43490. * and the exponent defines the speed of the decay of the light with distance (reach).
  43491. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43492. */
  43493. var SpotLight = /** @class */ (function (_super) {
  43494. __extends(SpotLight, _super);
  43495. /**
  43496. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  43497. * It can cast shadows.
  43498. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43499. * @param name The light friendly name
  43500. * @param position The position of the spot light in the scene
  43501. * @param direction The direction of the light in the scene
  43502. * @param angle The cone angle of the light in Radians
  43503. * @param exponent The light decay speed with the distance from the emission spot
  43504. * @param scene The scene the lights belongs to
  43505. */
  43506. function SpotLight(name, position, direction, angle, exponent, scene) {
  43507. var _this = _super.call(this, name, scene) || this;
  43508. _this._textureProjectionMatrix = BABYLON.Matrix.Zero();
  43509. _this.position = position;
  43510. _this.direction = direction;
  43511. _this.angle = angle;
  43512. _this.exponent = exponent;
  43513. return _this;
  43514. }
  43515. Object.defineProperty(SpotLight.prototype, "angle", {
  43516. get: function () {
  43517. return this._angle;
  43518. },
  43519. /**
  43520. * Sets the cone angle of the spot light in Radians.
  43521. */
  43522. set: function (value) {
  43523. this._angle = value;
  43524. this.forceProjectionMatrixCompute();
  43525. },
  43526. enumerable: true,
  43527. configurable: true
  43528. });
  43529. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43530. get: function () {
  43531. return this._shadowAngleScale;
  43532. },
  43533. /**
  43534. * Allows scaling the angle of the light for shadow generation only.
  43535. */
  43536. set: function (value) {
  43537. this._shadowAngleScale = value;
  43538. this.forceProjectionMatrixCompute();
  43539. },
  43540. enumerable: true,
  43541. configurable: true
  43542. });
  43543. Object.defineProperty(SpotLight.prototype, "textureMatrix", {
  43544. get: function () {
  43545. return this._textureProjectionMatrix;
  43546. },
  43547. /**
  43548. * Allows setting the value of projection texture
  43549. */
  43550. set: function (value) {
  43551. this._textureProjectionMatrix = value;
  43552. },
  43553. enumerable: true,
  43554. configurable: true
  43555. });
  43556. Object.defineProperty(SpotLight.prototype, "light_near", {
  43557. get: function () {
  43558. return this._light_near;
  43559. },
  43560. /**
  43561. * Sets the near clip of the Spotlight for texture projection.
  43562. */
  43563. set: function (value) {
  43564. this._light_near = value;
  43565. this._computeTextureMatrix();
  43566. },
  43567. enumerable: true,
  43568. configurable: true
  43569. });
  43570. Object.defineProperty(SpotLight.prototype, "light_far", {
  43571. /**
  43572. * Gets the far clip of the Spotlight for texture projection.
  43573. */
  43574. get: function () {
  43575. return this._light_far;
  43576. },
  43577. /**
  43578. * Sets the far clip of the Spotlight for texture projection.
  43579. */
  43580. set: function (value) {
  43581. this._light_far = value;
  43582. },
  43583. enumerable: true,
  43584. configurable: true
  43585. });
  43586. ;
  43587. Object.defineProperty(SpotLight.prototype, "projectedLightTexture", {
  43588. /**
  43589. * Gets the projection texture of the light.
  43590. */
  43591. get: function () {
  43592. return this._projectedLightTexture;
  43593. },
  43594. /**
  43595. * Sets the projection texture of the light.
  43596. */
  43597. set: function (value) {
  43598. this._projectedLightTexture = value;
  43599. this._light_far = 1000.0;
  43600. this._light_near = 1e-6;
  43601. this._computeTextureMatrix();
  43602. },
  43603. enumerable: true,
  43604. configurable: true
  43605. });
  43606. /**
  43607. * Returns the string "SpotLight".
  43608. * @returns the class name
  43609. */
  43610. SpotLight.prototype.getClassName = function () {
  43611. return "SpotLight";
  43612. };
  43613. /**
  43614. * Returns the integer 2.
  43615. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43616. */
  43617. SpotLight.prototype.getTypeID = function () {
  43618. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43619. };
  43620. /**
  43621. * 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.
  43622. * Returns the SpotLight.
  43623. */
  43624. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43625. var activeCamera = this.getScene().activeCamera;
  43626. if (!activeCamera) {
  43627. return;
  43628. }
  43629. this._shadowAngleScale = this._shadowAngleScale || 1;
  43630. var angle = this._shadowAngleScale * this._angle;
  43631. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43632. };
  43633. /**
  43634. * Main function for light texture projection matrix computing.
  43635. */
  43636. SpotLight.prototype._computeTextureMatrix = function () {
  43637. var viewLightMatrix = BABYLON.Matrix.Zero();
  43638. BABYLON.Matrix.LookAtLHToRef(this.position, this.position.add(this.direction), BABYLON.Vector3.Up(), viewLightMatrix);
  43639. var light_far = this.light_far;
  43640. var light_near = this.light_near;
  43641. var P = light_far / (light_far - light_near);
  43642. var Q = -P * light_near;
  43643. var S = 1.0 / Math.tan(this._angle / 2.0);
  43644. var A = 1.0;
  43645. var projectionLightMatrix = BABYLON.Matrix.Zero();
  43646. 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, projectionLightMatrix);
  43647. var scaleMatrix = BABYLON.Matrix.Zero();
  43648. BABYLON.Matrix.FromValuesToRef(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, scaleMatrix);
  43649. this._textureProjectionMatrix.copyFrom(viewLightMatrix);
  43650. this._textureProjectionMatrix.multiplyToRef(projectionLightMatrix, this._textureProjectionMatrix);
  43651. this._textureProjectionMatrix.multiplyToRef(scaleMatrix, this._textureProjectionMatrix);
  43652. };
  43653. SpotLight.prototype._buildUniformLayout = function () {
  43654. this._uniformBuffer.addUniform("vLightData", 4);
  43655. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43656. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43657. this._uniformBuffer.addUniform("vLightDirection", 3);
  43658. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43659. this._uniformBuffer.addUniform("depthValues", 2);
  43660. this._uniformBuffer.create();
  43661. };
  43662. /**
  43663. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43664. * @param effect The effect to update
  43665. * @param lightIndex The index of the light in the effect to update
  43666. * @returns The spot light
  43667. */
  43668. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43669. var normalizeDirection;
  43670. if (this.computeTransformedInformation()) {
  43671. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43672. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43673. }
  43674. else {
  43675. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43676. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43677. }
  43678. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43679. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._textureProjectionMatrix);
  43680. if (this.projectedLightTexture) {
  43681. effect.setTexture("projectionLightSampler" + lightIndex, this.projectedLightTexture);
  43682. }
  43683. return this;
  43684. };
  43685. /**
  43686. * Disposes the light and the associated resources.
  43687. */
  43688. SpotLight.prototype.dispose = function () {
  43689. _super.prototype.dispose.call(this);
  43690. if (this._projectedLightTexture) {
  43691. this._projectedLightTexture.dispose();
  43692. }
  43693. };
  43694. __decorate([
  43695. BABYLON.serialize()
  43696. /**
  43697. * Gets the cone angle of the spot light in Radians.
  43698. */
  43699. ], SpotLight.prototype, "angle", null);
  43700. __decorate([
  43701. BABYLON.serialize()
  43702. /**
  43703. * Allows scaling the angle of the light for shadow generation only.
  43704. */
  43705. ], SpotLight.prototype, "shadowAngleScale", null);
  43706. __decorate([
  43707. BABYLON.serialize()
  43708. ], SpotLight.prototype, "exponent", void 0);
  43709. __decorate([
  43710. BABYLON.serialize()
  43711. /**
  43712. * Allows reading the projecton texture
  43713. */
  43714. ], SpotLight.prototype, "textureMatrix", null);
  43715. __decorate([
  43716. BABYLON.serialize()
  43717. /**
  43718. * Gets the near clip of the Spotlight for texture projection.
  43719. */
  43720. ], SpotLight.prototype, "light_near", null);
  43721. __decorate([
  43722. BABYLON.serialize()
  43723. ], SpotLight.prototype, "light_far", null);
  43724. __decorate([
  43725. BABYLON.serializeAsTexture("projectedLightTexture")
  43726. ], SpotLight.prototype, "_projectedLightTexture", void 0);
  43727. return SpotLight;
  43728. }(BABYLON.ShadowLight));
  43729. BABYLON.SpotLight = SpotLight;
  43730. })(BABYLON || (BABYLON = {}));
  43731. //# sourceMappingURL=babylon.spotLight.js.map
  43732. var BABYLON;
  43733. (function (BABYLON) {
  43734. var AnimationRange = /** @class */ (function () {
  43735. function AnimationRange(name, from, to) {
  43736. this.name = name;
  43737. this.from = from;
  43738. this.to = to;
  43739. }
  43740. AnimationRange.prototype.clone = function () {
  43741. return new AnimationRange(this.name, this.from, this.to);
  43742. };
  43743. return AnimationRange;
  43744. }());
  43745. BABYLON.AnimationRange = AnimationRange;
  43746. /**
  43747. * Composed of a frame, and an action function
  43748. */
  43749. var AnimationEvent = /** @class */ (function () {
  43750. function AnimationEvent(frame, action, onlyOnce) {
  43751. this.frame = frame;
  43752. this.action = action;
  43753. this.onlyOnce = onlyOnce;
  43754. this.isDone = false;
  43755. }
  43756. return AnimationEvent;
  43757. }());
  43758. BABYLON.AnimationEvent = AnimationEvent;
  43759. var PathCursor = /** @class */ (function () {
  43760. function PathCursor(path) {
  43761. this.path = path;
  43762. this._onchange = new Array();
  43763. this.value = 0;
  43764. this.animations = new Array();
  43765. }
  43766. PathCursor.prototype.getPoint = function () {
  43767. var point = this.path.getPointAtLengthPosition(this.value);
  43768. return new BABYLON.Vector3(point.x, 0, point.y);
  43769. };
  43770. PathCursor.prototype.moveAhead = function (step) {
  43771. if (step === void 0) { step = 0.002; }
  43772. this.move(step);
  43773. return this;
  43774. };
  43775. PathCursor.prototype.moveBack = function (step) {
  43776. if (step === void 0) { step = 0.002; }
  43777. this.move(-step);
  43778. return this;
  43779. };
  43780. PathCursor.prototype.move = function (step) {
  43781. if (Math.abs(step) > 1) {
  43782. throw "step size should be less than 1.";
  43783. }
  43784. this.value += step;
  43785. this.ensureLimits();
  43786. this.raiseOnChange();
  43787. return this;
  43788. };
  43789. PathCursor.prototype.ensureLimits = function () {
  43790. while (this.value > 1) {
  43791. this.value -= 1;
  43792. }
  43793. while (this.value < 0) {
  43794. this.value += 1;
  43795. }
  43796. return this;
  43797. };
  43798. // used by animation engine
  43799. PathCursor.prototype.raiseOnChange = function () {
  43800. var _this = this;
  43801. this._onchange.forEach(function (f) { return f(_this); });
  43802. return this;
  43803. };
  43804. PathCursor.prototype.onchange = function (f) {
  43805. this._onchange.push(f);
  43806. return this;
  43807. };
  43808. return PathCursor;
  43809. }());
  43810. BABYLON.PathCursor = PathCursor;
  43811. var AnimationKeyInterpolation;
  43812. (function (AnimationKeyInterpolation) {
  43813. /**
  43814. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  43815. */
  43816. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43817. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43818. var Animation = /** @class */ (function () {
  43819. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43820. this.name = name;
  43821. this.targetProperty = targetProperty;
  43822. this.framePerSecond = framePerSecond;
  43823. this.dataType = dataType;
  43824. this.loopMode = loopMode;
  43825. this.enableBlending = enableBlending;
  43826. this._runtimeAnimations = new Array();
  43827. // The set of event that will be linked to this animation
  43828. this._events = new Array();
  43829. this.blendingSpeed = 0.01;
  43830. this._ranges = {};
  43831. this.targetPropertyPath = targetProperty.split(".");
  43832. this.dataType = dataType;
  43833. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43834. }
  43835. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43836. var dataType = undefined;
  43837. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43838. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43839. }
  43840. else if (from instanceof BABYLON.Quaternion) {
  43841. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43842. }
  43843. else if (from instanceof BABYLON.Vector3) {
  43844. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43845. }
  43846. else if (from instanceof BABYLON.Vector2) {
  43847. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43848. }
  43849. else if (from instanceof BABYLON.Color3) {
  43850. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43851. }
  43852. else if (from instanceof BABYLON.Size) {
  43853. dataType = Animation.ANIMATIONTYPE_SIZE;
  43854. }
  43855. if (dataType == undefined) {
  43856. return null;
  43857. }
  43858. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43859. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43860. animation.setKeys(keys);
  43861. if (easingFunction !== undefined) {
  43862. animation.setEasingFunction(easingFunction);
  43863. }
  43864. return animation;
  43865. };
  43866. /**
  43867. * Sets up an animation.
  43868. * @param property the property to animate
  43869. * @param animationType the animation type to apply
  43870. * @param easingFunction the easing function used in the animation
  43871. * @returns The created animation
  43872. */
  43873. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43874. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43875. animation.setEasingFunction(easingFunction);
  43876. return animation;
  43877. };
  43878. /**
  43879. * Create and start an animation on a node
  43880. * @param {string} name defines the name of the global animation that will be run on all nodes
  43881. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43882. * @param {string} targetProperty defines property to animate
  43883. * @param {number} framePerSecond defines the number of frame per second yo use
  43884. * @param {number} totalFrame defines the number of frames in total
  43885. * @param {any} from defines the initial value
  43886. * @param {any} to defines the final value
  43887. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43888. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43889. * @param onAnimationEnd defines the callback to call when animation end
  43890. * @returns the animatable created for this animation
  43891. */
  43892. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43893. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43894. if (!animation) {
  43895. return null;
  43896. }
  43897. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43898. };
  43899. /**
  43900. * Create and start an animation on a node and its descendants
  43901. * @param {string} name defines the name of the global animation that will be run on all nodes
  43902. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43903. * @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.
  43904. * @param {string} targetProperty defines property to animate
  43905. * @param {number} framePerSecond defines the number of frame per second yo use
  43906. * @param {number} totalFrame defines the number of frames in total
  43907. * @param {any} from defines the initial value
  43908. * @param {any} to defines the final value
  43909. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43910. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43911. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43912. * @returns the list of animatables created for all nodes
  43913. * @example https://www.babylonjs-playground.com/#MH0VLI
  43914. */
  43915. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43916. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43917. if (!animation) {
  43918. return null;
  43919. }
  43920. var scene = node.getScene();
  43921. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43922. };
  43923. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43924. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43925. if (!animation) {
  43926. return null;
  43927. }
  43928. node.animations.push(animation);
  43929. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43930. };
  43931. /**
  43932. * Transition property of the Camera to the target Value.
  43933. * @param property The property to transition
  43934. * @param targetValue The target Value of the property
  43935. * @param host The object where the property to animate belongs
  43936. * @param scene Scene used to run the animation
  43937. * @param frameRate Framerate (in frame/s) to use
  43938. * @param transition The transition type we want to use
  43939. * @param duration The duration of the animation, in milliseconds
  43940. * @param onAnimationEnd Call back trigger at the end of the animation.
  43941. */
  43942. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43943. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43944. if (duration <= 0) {
  43945. host[property] = targetValue;
  43946. if (onAnimationEnd) {
  43947. onAnimationEnd();
  43948. }
  43949. return null;
  43950. }
  43951. var endFrame = frameRate * (duration / 1000);
  43952. transition.setKeys([{
  43953. frame: 0,
  43954. value: host[property].clone ? host[property].clone() : host[property]
  43955. },
  43956. {
  43957. frame: endFrame,
  43958. value: targetValue
  43959. }]);
  43960. if (!host.animations) {
  43961. host.animations = [];
  43962. }
  43963. host.animations.push(transition);
  43964. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43965. animation.onAnimationEnd = onAnimationEnd;
  43966. return animation;
  43967. };
  43968. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43969. /**
  43970. * Return the array of runtime animations currently using this animation
  43971. */
  43972. get: function () {
  43973. return this._runtimeAnimations;
  43974. },
  43975. enumerable: true,
  43976. configurable: true
  43977. });
  43978. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43979. get: function () {
  43980. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43981. var runtimeAnimation = _a[_i];
  43982. if (!runtimeAnimation.isStopped) {
  43983. return true;
  43984. }
  43985. }
  43986. return false;
  43987. },
  43988. enumerable: true,
  43989. configurable: true
  43990. });
  43991. // Methods
  43992. /**
  43993. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43994. */
  43995. Animation.prototype.toString = function (fullDetails) {
  43996. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43997. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43998. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43999. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  44000. if (fullDetails) {
  44001. ret += ", Ranges: {";
  44002. var first = true;
  44003. for (var name in this._ranges) {
  44004. if (first) {
  44005. ret += ", ";
  44006. first = false;
  44007. }
  44008. ret += name;
  44009. }
  44010. ret += "}";
  44011. }
  44012. return ret;
  44013. };
  44014. /**
  44015. * Add an event to this animation.
  44016. */
  44017. Animation.prototype.addEvent = function (event) {
  44018. this._events.push(event);
  44019. };
  44020. /**
  44021. * Remove all events found at the given frame
  44022. * @param frame
  44023. */
  44024. Animation.prototype.removeEvents = function (frame) {
  44025. for (var index = 0; index < this._events.length; index++) {
  44026. if (this._events[index].frame === frame) {
  44027. this._events.splice(index, 1);
  44028. index--;
  44029. }
  44030. }
  44031. };
  44032. Animation.prototype.getEvents = function () {
  44033. return this._events;
  44034. };
  44035. Animation.prototype.createRange = function (name, from, to) {
  44036. // check name not already in use; could happen for bones after serialized
  44037. if (!this._ranges[name]) {
  44038. this._ranges[name] = new AnimationRange(name, from, to);
  44039. }
  44040. };
  44041. Animation.prototype.deleteRange = function (name, deleteFrames) {
  44042. if (deleteFrames === void 0) { deleteFrames = true; }
  44043. var range = this._ranges[name];
  44044. if (!range) {
  44045. return;
  44046. }
  44047. if (deleteFrames) {
  44048. var from = range.from;
  44049. var to = range.to;
  44050. // this loop MUST go high to low for multiple splices to work
  44051. for (var key = this._keys.length - 1; key >= 0; key--) {
  44052. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  44053. this._keys.splice(key, 1);
  44054. }
  44055. }
  44056. }
  44057. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  44058. };
  44059. Animation.prototype.getRange = function (name) {
  44060. return this._ranges[name];
  44061. };
  44062. Animation.prototype.getKeys = function () {
  44063. return this._keys;
  44064. };
  44065. Animation.prototype.getHighestFrame = function () {
  44066. var ret = 0;
  44067. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  44068. if (ret < this._keys[key].frame) {
  44069. ret = this._keys[key].frame;
  44070. }
  44071. }
  44072. return ret;
  44073. };
  44074. Animation.prototype.getEasingFunction = function () {
  44075. return this._easingFunction;
  44076. };
  44077. Animation.prototype.setEasingFunction = function (easingFunction) {
  44078. this._easingFunction = easingFunction;
  44079. };
  44080. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  44081. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  44082. };
  44083. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44084. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44085. };
  44086. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  44087. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  44088. };
  44089. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44090. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  44091. };
  44092. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  44093. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  44094. };
  44095. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44096. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44097. };
  44098. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  44099. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  44100. };
  44101. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44102. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44103. };
  44104. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  44105. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  44106. };
  44107. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  44108. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  44109. };
  44110. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  44111. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  44112. };
  44113. Animation.prototype.clone = function () {
  44114. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  44115. clone.enableBlending = this.enableBlending;
  44116. clone.blendingSpeed = this.blendingSpeed;
  44117. if (this._keys) {
  44118. clone.setKeys(this._keys);
  44119. }
  44120. if (this._ranges) {
  44121. clone._ranges = {};
  44122. for (var name in this._ranges) {
  44123. var range = this._ranges[name];
  44124. if (!range) {
  44125. continue;
  44126. }
  44127. clone._ranges[name] = range.clone();
  44128. }
  44129. }
  44130. return clone;
  44131. };
  44132. Animation.prototype.setKeys = function (values) {
  44133. this._keys = values.slice(0);
  44134. };
  44135. Animation.prototype.serialize = function () {
  44136. var serializationObject = {};
  44137. serializationObject.name = this.name;
  44138. serializationObject.property = this.targetProperty;
  44139. serializationObject.framePerSecond = this.framePerSecond;
  44140. serializationObject.dataType = this.dataType;
  44141. serializationObject.loopBehavior = this.loopMode;
  44142. serializationObject.enableBlending = this.enableBlending;
  44143. serializationObject.blendingSpeed = this.blendingSpeed;
  44144. var dataType = this.dataType;
  44145. serializationObject.keys = [];
  44146. var keys = this.getKeys();
  44147. for (var index = 0; index < keys.length; index++) {
  44148. var animationKey = keys[index];
  44149. var key = {};
  44150. key.frame = animationKey.frame;
  44151. switch (dataType) {
  44152. case Animation.ANIMATIONTYPE_FLOAT:
  44153. key.values = [animationKey.value];
  44154. break;
  44155. case Animation.ANIMATIONTYPE_QUATERNION:
  44156. case Animation.ANIMATIONTYPE_MATRIX:
  44157. case Animation.ANIMATIONTYPE_VECTOR3:
  44158. case Animation.ANIMATIONTYPE_COLOR3:
  44159. key.values = animationKey.value.asArray();
  44160. break;
  44161. }
  44162. serializationObject.keys.push(key);
  44163. }
  44164. serializationObject.ranges = [];
  44165. for (var name in this._ranges) {
  44166. var source = this._ranges[name];
  44167. if (!source) {
  44168. continue;
  44169. }
  44170. var range = {};
  44171. range.name = name;
  44172. range.from = source.from;
  44173. range.to = source.to;
  44174. serializationObject.ranges.push(range);
  44175. }
  44176. return serializationObject;
  44177. };
  44178. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  44179. get: function () {
  44180. return Animation._ANIMATIONTYPE_FLOAT;
  44181. },
  44182. enumerable: true,
  44183. configurable: true
  44184. });
  44185. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  44186. get: function () {
  44187. return Animation._ANIMATIONTYPE_VECTOR3;
  44188. },
  44189. enumerable: true,
  44190. configurable: true
  44191. });
  44192. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  44193. get: function () {
  44194. return Animation._ANIMATIONTYPE_VECTOR2;
  44195. },
  44196. enumerable: true,
  44197. configurable: true
  44198. });
  44199. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  44200. get: function () {
  44201. return Animation._ANIMATIONTYPE_SIZE;
  44202. },
  44203. enumerable: true,
  44204. configurable: true
  44205. });
  44206. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  44207. get: function () {
  44208. return Animation._ANIMATIONTYPE_QUATERNION;
  44209. },
  44210. enumerable: true,
  44211. configurable: true
  44212. });
  44213. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  44214. get: function () {
  44215. return Animation._ANIMATIONTYPE_MATRIX;
  44216. },
  44217. enumerable: true,
  44218. configurable: true
  44219. });
  44220. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  44221. get: function () {
  44222. return Animation._ANIMATIONTYPE_COLOR3;
  44223. },
  44224. enumerable: true,
  44225. configurable: true
  44226. });
  44227. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  44228. get: function () {
  44229. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  44230. },
  44231. enumerable: true,
  44232. configurable: true
  44233. });
  44234. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  44235. get: function () {
  44236. return Animation._ANIMATIONLOOPMODE_CYCLE;
  44237. },
  44238. enumerable: true,
  44239. configurable: true
  44240. });
  44241. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  44242. get: function () {
  44243. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  44244. },
  44245. enumerable: true,
  44246. configurable: true
  44247. });
  44248. Animation.Parse = function (parsedAnimation) {
  44249. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  44250. var dataType = parsedAnimation.dataType;
  44251. var keys = [];
  44252. var data;
  44253. var index;
  44254. if (parsedAnimation.enableBlending) {
  44255. animation.enableBlending = parsedAnimation.enableBlending;
  44256. }
  44257. if (parsedAnimation.blendingSpeed) {
  44258. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  44259. }
  44260. for (index = 0; index < parsedAnimation.keys.length; index++) {
  44261. var key = parsedAnimation.keys[index];
  44262. var inTangent;
  44263. var outTangent;
  44264. switch (dataType) {
  44265. case Animation.ANIMATIONTYPE_FLOAT:
  44266. data = key.values[0];
  44267. if (key.values.length >= 1) {
  44268. inTangent = key.values[1];
  44269. }
  44270. if (key.values.length >= 2) {
  44271. outTangent = key.values[2];
  44272. }
  44273. break;
  44274. case Animation.ANIMATIONTYPE_QUATERNION:
  44275. data = BABYLON.Quaternion.FromArray(key.values);
  44276. if (key.values.length >= 8) {
  44277. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  44278. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  44279. inTangent = _inTangent;
  44280. }
  44281. }
  44282. if (key.values.length >= 12) {
  44283. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  44284. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  44285. outTangent = _outTangent;
  44286. }
  44287. }
  44288. break;
  44289. case Animation.ANIMATIONTYPE_MATRIX:
  44290. data = BABYLON.Matrix.FromArray(key.values);
  44291. break;
  44292. case Animation.ANIMATIONTYPE_COLOR3:
  44293. data = BABYLON.Color3.FromArray(key.values);
  44294. break;
  44295. case Animation.ANIMATIONTYPE_VECTOR3:
  44296. default:
  44297. data = BABYLON.Vector3.FromArray(key.values);
  44298. break;
  44299. }
  44300. var keyData = {};
  44301. keyData.frame = key.frame;
  44302. keyData.value = data;
  44303. if (inTangent != undefined) {
  44304. keyData.inTangent = inTangent;
  44305. }
  44306. if (outTangent != undefined) {
  44307. keyData.outTangent = outTangent;
  44308. }
  44309. keys.push(keyData);
  44310. }
  44311. animation.setKeys(keys);
  44312. if (parsedAnimation.ranges) {
  44313. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  44314. data = parsedAnimation.ranges[index];
  44315. animation.createRange(data.name, data.from, data.to);
  44316. }
  44317. }
  44318. return animation;
  44319. };
  44320. Animation.AppendSerializedAnimations = function (source, destination) {
  44321. if (source.animations) {
  44322. destination.animations = [];
  44323. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  44324. var animation = source.animations[animationIndex];
  44325. destination.animations.push(animation.serialize());
  44326. }
  44327. }
  44328. };
  44329. Animation.AllowMatricesInterpolation = false;
  44330. // Statics
  44331. Animation._ANIMATIONTYPE_FLOAT = 0;
  44332. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  44333. Animation._ANIMATIONTYPE_QUATERNION = 2;
  44334. Animation._ANIMATIONTYPE_MATRIX = 3;
  44335. Animation._ANIMATIONTYPE_COLOR3 = 4;
  44336. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  44337. Animation._ANIMATIONTYPE_SIZE = 6;
  44338. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  44339. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  44340. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  44341. return Animation;
  44342. }());
  44343. BABYLON.Animation = Animation;
  44344. })(BABYLON || (BABYLON = {}));
  44345. //# sourceMappingURL=babylon.animation.js.map
  44346. var BABYLON;
  44347. (function (BABYLON) {
  44348. /**
  44349. * This class defines the direct association between an animation and a target
  44350. */
  44351. var TargetedAnimation = /** @class */ (function () {
  44352. function TargetedAnimation() {
  44353. }
  44354. return TargetedAnimation;
  44355. }());
  44356. BABYLON.TargetedAnimation = TargetedAnimation;
  44357. /**
  44358. * Use this class to create coordinated animations on multiple targets
  44359. */
  44360. var AnimationGroup = /** @class */ (function () {
  44361. function AnimationGroup(name, scene) {
  44362. if (scene === void 0) { scene = null; }
  44363. this.name = name;
  44364. this._targetedAnimations = new Array();
  44365. this._animatables = new Array();
  44366. this._from = Number.MAX_VALUE;
  44367. this._to = -Number.MAX_VALUE;
  44368. this._speedRatio = 1;
  44369. this.onAnimationEndObservable = new BABYLON.Observable();
  44370. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44371. this._scene.animationGroups.push(this);
  44372. }
  44373. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  44374. /**
  44375. * Define if the animations are started
  44376. */
  44377. get: function () {
  44378. return this._isStarted;
  44379. },
  44380. enumerable: true,
  44381. configurable: true
  44382. });
  44383. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  44384. /**
  44385. * Gets or sets the speed ratio to use for all animations
  44386. */
  44387. get: function () {
  44388. return this._speedRatio;
  44389. },
  44390. /**
  44391. * Gets or sets the speed ratio to use for all animations
  44392. */
  44393. set: function (value) {
  44394. if (this._speedRatio === value) {
  44395. return;
  44396. }
  44397. this._speedRatio = value;
  44398. for (var index = 0; index < this._animatables.length; index++) {
  44399. var animatable = this._animatables[index];
  44400. animatable.speedRatio = this._speedRatio;
  44401. }
  44402. },
  44403. enumerable: true,
  44404. configurable: true
  44405. });
  44406. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  44407. /**
  44408. * Gets the targeted animations for this animation group
  44409. */
  44410. get: function () {
  44411. return this._targetedAnimations;
  44412. },
  44413. enumerable: true,
  44414. configurable: true
  44415. });
  44416. /**
  44417. * Add an animation (with its target) in the group
  44418. * @param animation defines the animation we want to add
  44419. * @param target defines the target of the animation
  44420. * @returns the {BABYLON.TargetedAnimation} object
  44421. */
  44422. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  44423. var targetedAnimation = {
  44424. animation: animation,
  44425. target: target
  44426. };
  44427. var keys = animation.getKeys();
  44428. if (this._from > keys[0].frame) {
  44429. this._from = keys[0].frame;
  44430. }
  44431. if (this._to < keys[keys.length - 1].frame) {
  44432. this._to = keys[keys.length - 1].frame;
  44433. }
  44434. this._targetedAnimations.push(targetedAnimation);
  44435. return targetedAnimation;
  44436. };
  44437. /**
  44438. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  44439. * It can add constant keys at begin or end
  44440. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  44441. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  44442. */
  44443. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  44444. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  44445. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  44446. beginFrame = Math.max(beginFrame, this._from);
  44447. endFrame = Math.min(endFrame, this._to);
  44448. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44449. var targetedAnimation = this._targetedAnimations[index];
  44450. var keys = targetedAnimation.animation.getKeys();
  44451. var startKey = keys[0];
  44452. var endKey = keys[keys.length - 1];
  44453. if (startKey.frame > beginFrame) {
  44454. var newKey = {
  44455. frame: beginFrame,
  44456. value: startKey.value,
  44457. inTangent: startKey.inTangent,
  44458. outTangent: startKey.outTangent,
  44459. interpolation: startKey.interpolation
  44460. };
  44461. keys.splice(0, 0, newKey);
  44462. }
  44463. if (endKey.frame < endFrame) {
  44464. var newKey = {
  44465. frame: endFrame,
  44466. value: endKey.value,
  44467. inTangent: endKey.outTangent,
  44468. outTangent: endKey.outTangent,
  44469. interpolation: endKey.interpolation
  44470. };
  44471. keys.push(newKey);
  44472. }
  44473. }
  44474. return this;
  44475. };
  44476. /**
  44477. * Start all animations on given targets
  44478. * @param loop defines if animations must loop
  44479. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  44480. */
  44481. AnimationGroup.prototype.start = function (loop, speedRatio) {
  44482. var _this = this;
  44483. if (loop === void 0) { loop = false; }
  44484. if (speedRatio === void 0) { speedRatio = 1; }
  44485. if (this._isStarted || this._targetedAnimations.length === 0) {
  44486. return this;
  44487. }
  44488. var _loop_1 = function () {
  44489. var targetedAnimation = this_1._targetedAnimations[index];
  44490. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  44491. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  44492. }));
  44493. };
  44494. var this_1 = this;
  44495. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44496. _loop_1();
  44497. }
  44498. this._speedRatio = speedRatio;
  44499. this._isStarted = true;
  44500. return this;
  44501. };
  44502. /**
  44503. * Pause all animations
  44504. */
  44505. AnimationGroup.prototype.pause = function () {
  44506. if (!this._isStarted) {
  44507. return this;
  44508. }
  44509. for (var index = 0; index < this._animatables.length; index++) {
  44510. var animatable = this._animatables[index];
  44511. animatable.pause();
  44512. }
  44513. return this;
  44514. };
  44515. /**
  44516. * Play all animations to initial state
  44517. * This function will start() the animations if they were not started or will restart() them if they were paused
  44518. * @param loop defines if animations must loop
  44519. */
  44520. AnimationGroup.prototype.play = function (loop) {
  44521. if (this.isStarted) {
  44522. if (loop !== undefined) {
  44523. for (var index = 0; index < this._animatables.length; index++) {
  44524. var animatable = this._animatables[index];
  44525. animatable.loopAnimation = loop;
  44526. }
  44527. }
  44528. this.restart();
  44529. }
  44530. else {
  44531. this.start(loop, this._speedRatio);
  44532. }
  44533. return this;
  44534. };
  44535. /**
  44536. * Reset all animations to initial state
  44537. */
  44538. AnimationGroup.prototype.reset = function () {
  44539. if (!this._isStarted) {
  44540. return this;
  44541. }
  44542. for (var index = 0; index < this._animatables.length; index++) {
  44543. var animatable = this._animatables[index];
  44544. animatable.reset();
  44545. }
  44546. return this;
  44547. };
  44548. /**
  44549. * Restart animations from key 0
  44550. */
  44551. AnimationGroup.prototype.restart = function () {
  44552. if (!this._isStarted) {
  44553. return this;
  44554. }
  44555. for (var index = 0; index < this._animatables.length; index++) {
  44556. var animatable = this._animatables[index];
  44557. animatable.restart();
  44558. }
  44559. return this;
  44560. };
  44561. /**
  44562. * Stop all animations
  44563. */
  44564. AnimationGroup.prototype.stop = function () {
  44565. if (!this._isStarted) {
  44566. return this;
  44567. }
  44568. for (var index = 0; index < this._animatables.length; index++) {
  44569. var animatable = this._animatables[index];
  44570. animatable.stop();
  44571. }
  44572. this._isStarted = false;
  44573. return this;
  44574. };
  44575. /**
  44576. * Dispose all associated resources
  44577. */
  44578. AnimationGroup.prototype.dispose = function () {
  44579. this._targetedAnimations = [];
  44580. this._animatables = [];
  44581. var index = this._scene.animationGroups.indexOf(this);
  44582. if (index > -1) {
  44583. this._scene.animationGroups.splice(index, 1);
  44584. }
  44585. };
  44586. return AnimationGroup;
  44587. }());
  44588. BABYLON.AnimationGroup = AnimationGroup;
  44589. })(BABYLON || (BABYLON = {}));
  44590. //# sourceMappingURL=babylon.animationGroup.js.map
  44591. var BABYLON;
  44592. (function (BABYLON) {
  44593. var RuntimeAnimation = /** @class */ (function () {
  44594. function RuntimeAnimation(target, animation) {
  44595. this._offsetsCache = {};
  44596. this._highLimitsCache = {};
  44597. this._stopped = false;
  44598. this._blendingFactor = 0;
  44599. this._ratioOffset = 0;
  44600. this._animation = animation;
  44601. this._target = target;
  44602. animation._runtimeAnimations.push(this);
  44603. }
  44604. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44605. get: function () {
  44606. return this._animation;
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. RuntimeAnimation.prototype.reset = function () {
  44612. this._offsetsCache = {};
  44613. this._highLimitsCache = {};
  44614. this.currentFrame = 0;
  44615. this._blendingFactor = 0;
  44616. this._originalBlendValue = null;
  44617. };
  44618. RuntimeAnimation.prototype.isStopped = function () {
  44619. return this._stopped;
  44620. };
  44621. RuntimeAnimation.prototype.dispose = function () {
  44622. var index = this._animation.runtimeAnimations.indexOf(this);
  44623. if (index > -1) {
  44624. this._animation.runtimeAnimations.splice(index, 1);
  44625. }
  44626. };
  44627. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44628. if (typeof value === "function") {
  44629. return value();
  44630. }
  44631. return value;
  44632. };
  44633. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44634. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44635. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44636. }
  44637. this.currentFrame = currentFrame;
  44638. var keys = this._animation.getKeys();
  44639. // Try to get a hash to find the right key
  44640. 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));
  44641. if (keys[startKeyIndex].frame >= currentFrame) {
  44642. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44643. startKeyIndex--;
  44644. }
  44645. }
  44646. for (var key = startKeyIndex; key < keys.length; key++) {
  44647. var endKey = keys[key + 1];
  44648. if (endKey.frame >= currentFrame) {
  44649. var startKey = keys[key];
  44650. var startValue = this._getKeyValue(startKey.value);
  44651. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44652. return startValue;
  44653. }
  44654. var endValue = this._getKeyValue(endKey.value);
  44655. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44656. var frameDelta = endKey.frame - startKey.frame;
  44657. // gradient : percent of currentFrame between the frame inf and the frame sup
  44658. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44659. // check for easingFunction and correction of gradient
  44660. var easingFunction = this._animation.getEasingFunction();
  44661. if (easingFunction != null) {
  44662. gradient = easingFunction.ease(gradient);
  44663. }
  44664. switch (this._animation.dataType) {
  44665. // Float
  44666. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44667. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44668. switch (loopMode) {
  44669. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44670. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44671. return floatValue;
  44672. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44673. return offsetValue * repeatCount + floatValue;
  44674. }
  44675. break;
  44676. // Quaternion
  44677. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44678. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44679. switch (loopMode) {
  44680. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44681. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44682. return quatValue;
  44683. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44684. return quatValue.add(offsetValue.scale(repeatCount));
  44685. }
  44686. return quatValue;
  44687. // Vector3
  44688. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44689. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44690. switch (loopMode) {
  44691. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44692. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44693. return vec3Value;
  44694. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44695. return vec3Value.add(offsetValue.scale(repeatCount));
  44696. }
  44697. // Vector2
  44698. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44699. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44700. switch (loopMode) {
  44701. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44702. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44703. return vec2Value;
  44704. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44705. return vec2Value.add(offsetValue.scale(repeatCount));
  44706. }
  44707. // Size
  44708. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44709. switch (loopMode) {
  44710. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44711. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44712. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44713. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44714. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44715. }
  44716. // Color3
  44717. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44718. switch (loopMode) {
  44719. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44720. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44721. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44722. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44723. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44724. }
  44725. // Matrix
  44726. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44727. switch (loopMode) {
  44728. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44729. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44730. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44731. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44732. }
  44733. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44734. return startValue;
  44735. }
  44736. default:
  44737. break;
  44738. }
  44739. break;
  44740. }
  44741. }
  44742. return this._getKeyValue(keys[keys.length - 1].value);
  44743. };
  44744. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44745. if (blend === void 0) { blend = false; }
  44746. // Set value
  44747. var path;
  44748. var destination;
  44749. var targetPropertyPath = this._animation.targetPropertyPath;
  44750. if (targetPropertyPath.length > 1) {
  44751. var property = this._target[targetPropertyPath[0]];
  44752. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44753. property = property[targetPropertyPath[index]];
  44754. }
  44755. path = targetPropertyPath[targetPropertyPath.length - 1];
  44756. destination = property;
  44757. }
  44758. else {
  44759. path = targetPropertyPath[0];
  44760. destination = this._target;
  44761. }
  44762. // Blending
  44763. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44764. if (!this._originalBlendValue) {
  44765. if (destination[path].clone) {
  44766. this._originalBlendValue = destination[path].clone();
  44767. }
  44768. else {
  44769. this._originalBlendValue = destination[path];
  44770. }
  44771. }
  44772. if (this._originalBlendValue.prototype) {
  44773. if (this._originalBlendValue.prototype.Lerp) {
  44774. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  44775. }
  44776. else {
  44777. destination[path] = currentValue;
  44778. }
  44779. }
  44780. else if (this._originalBlendValue.m) {
  44781. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  44782. }
  44783. else {
  44784. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  44785. }
  44786. this._blendingFactor += this._animation.blendingSpeed;
  44787. }
  44788. else {
  44789. destination[path] = currentValue;
  44790. }
  44791. if (this._target.markAsDirty) {
  44792. this._target.markAsDirty(this._animation.targetProperty);
  44793. }
  44794. };
  44795. RuntimeAnimation.prototype.goToFrame = function (frame) {
  44796. var keys = this._animation.getKeys();
  44797. if (frame < keys[0].frame) {
  44798. frame = keys[0].frame;
  44799. }
  44800. else if (frame > keys[keys.length - 1].frame) {
  44801. frame = keys[keys.length - 1].frame;
  44802. }
  44803. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  44804. this.setValue(currentValue);
  44805. };
  44806. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  44807. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  44808. this._ratioOffset = this._previousRatio - newRatio;
  44809. };
  44810. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  44811. if (blend === void 0) { blend = false; }
  44812. var targetPropertyPath = this._animation.targetPropertyPath;
  44813. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  44814. this._stopped = true;
  44815. return false;
  44816. }
  44817. var returnValue = true;
  44818. var keys = this._animation.getKeys();
  44819. // Adding a start key at frame 0 if missing
  44820. if (keys[0].frame !== 0) {
  44821. var newKey = { frame: 0, value: keys[0].value };
  44822. keys.splice(0, 0, newKey);
  44823. }
  44824. // Check limits
  44825. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44826. from = keys[0].frame;
  44827. }
  44828. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44829. to = keys[keys.length - 1].frame;
  44830. }
  44831. //to and from cannot be the same key
  44832. if (from === to) {
  44833. if (from > keys[0].frame) {
  44834. from--;
  44835. }
  44836. else if (to < keys[keys.length - 1].frame) {
  44837. to++;
  44838. }
  44839. }
  44840. // Compute ratio
  44841. var range = to - from;
  44842. var offsetValue;
  44843. // ratio represents the frame delta between from and to
  44844. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44845. var highLimitValue = 0;
  44846. this._previousDelay = delay;
  44847. this._previousRatio = ratio;
  44848. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44849. returnValue = false;
  44850. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44851. }
  44852. else {
  44853. // Get max value if required
  44854. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44855. var keyOffset = to.toString() + from.toString();
  44856. if (!this._offsetsCache[keyOffset]) {
  44857. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44858. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44859. switch (this._animation.dataType) {
  44860. // Float
  44861. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44862. this._offsetsCache[keyOffset] = toValue - fromValue;
  44863. break;
  44864. // Quaternion
  44865. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44866. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44867. break;
  44868. // Vector3
  44869. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44870. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44871. // Vector2
  44872. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44873. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44874. // Size
  44875. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44876. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44877. // Color3
  44878. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44879. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44880. default:
  44881. break;
  44882. }
  44883. this._highLimitsCache[keyOffset] = toValue;
  44884. }
  44885. highLimitValue = this._highLimitsCache[keyOffset];
  44886. offsetValue = this._offsetsCache[keyOffset];
  44887. }
  44888. }
  44889. if (offsetValue === undefined) {
  44890. switch (this._animation.dataType) {
  44891. // Float
  44892. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44893. offsetValue = 0;
  44894. break;
  44895. // Quaternion
  44896. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44897. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44898. break;
  44899. // Vector3
  44900. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44901. offsetValue = BABYLON.Vector3.Zero();
  44902. break;
  44903. // Vector2
  44904. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44905. offsetValue = BABYLON.Vector2.Zero();
  44906. break;
  44907. // Size
  44908. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44909. offsetValue = BABYLON.Size.Zero();
  44910. break;
  44911. // Color3
  44912. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44913. offsetValue = BABYLON.Color3.Black();
  44914. }
  44915. }
  44916. // Compute value
  44917. var repeatCount = (ratio / range) >> 0;
  44918. var currentFrame = returnValue ? from + ratio % range : to;
  44919. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44920. // Set value
  44921. this.setValue(currentValue);
  44922. // Check events
  44923. var events = this._animation.getEvents();
  44924. for (var index = 0; index < events.length; index++) {
  44925. // Make sure current frame has passed event frame and that event frame is within the current range
  44926. // Also, handle both forward and reverse animations
  44927. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44928. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44929. var event = events[index];
  44930. if (!event.isDone) {
  44931. // If event should be done only once, remove it.
  44932. if (event.onlyOnce) {
  44933. events.splice(index, 1);
  44934. index--;
  44935. }
  44936. event.isDone = true;
  44937. event.action();
  44938. } // Don't do anything if the event has already be done.
  44939. }
  44940. else if (events[index].isDone && !events[index].onlyOnce) {
  44941. // reset event, the animation is looping
  44942. events[index].isDone = false;
  44943. }
  44944. }
  44945. if (!returnValue) {
  44946. this._stopped = true;
  44947. }
  44948. return returnValue;
  44949. };
  44950. return RuntimeAnimation;
  44951. }());
  44952. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44953. })(BABYLON || (BABYLON = {}));
  44954. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44955. var BABYLON;
  44956. (function (BABYLON) {
  44957. var Animatable = /** @class */ (function () {
  44958. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44959. if (fromFrame === void 0) { fromFrame = 0; }
  44960. if (toFrame === void 0) { toFrame = 100; }
  44961. if (loopAnimation === void 0) { loopAnimation = false; }
  44962. if (speedRatio === void 0) { speedRatio = 1.0; }
  44963. this.target = target;
  44964. this.fromFrame = fromFrame;
  44965. this.toFrame = toFrame;
  44966. this.loopAnimation = loopAnimation;
  44967. this.onAnimationEnd = onAnimationEnd;
  44968. this._localDelayOffset = null;
  44969. this._pausedDelay = null;
  44970. this._runtimeAnimations = new Array();
  44971. this._paused = false;
  44972. this._speedRatio = 1;
  44973. this.animationStarted = false;
  44974. if (animations) {
  44975. this.appendAnimations(target, animations);
  44976. }
  44977. this._speedRatio = speedRatio;
  44978. this._scene = scene;
  44979. scene._activeAnimatables.push(this);
  44980. }
  44981. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44982. get: function () {
  44983. return this._speedRatio;
  44984. },
  44985. set: function (value) {
  44986. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44987. var animation = this._runtimeAnimations[index];
  44988. animation._prepareForSpeedRatioChange(value);
  44989. }
  44990. this._speedRatio = value;
  44991. },
  44992. enumerable: true,
  44993. configurable: true
  44994. });
  44995. // Methods
  44996. Animatable.prototype.getAnimations = function () {
  44997. return this._runtimeAnimations;
  44998. };
  44999. Animatable.prototype.appendAnimations = function (target, animations) {
  45000. for (var index = 0; index < animations.length; index++) {
  45001. var animation = animations[index];
  45002. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  45003. }
  45004. };
  45005. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  45006. var runtimeAnimations = this._runtimeAnimations;
  45007. for (var index = 0; index < runtimeAnimations.length; index++) {
  45008. if (runtimeAnimations[index].animation.targetProperty === property) {
  45009. return runtimeAnimations[index].animation;
  45010. }
  45011. }
  45012. return null;
  45013. };
  45014. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  45015. var runtimeAnimations = this._runtimeAnimations;
  45016. for (var index = 0; index < runtimeAnimations.length; index++) {
  45017. if (runtimeAnimations[index].animation.targetProperty === property) {
  45018. return runtimeAnimations[index];
  45019. }
  45020. }
  45021. return null;
  45022. };
  45023. Animatable.prototype.reset = function () {
  45024. var runtimeAnimations = this._runtimeAnimations;
  45025. for (var index = 0; index < runtimeAnimations.length; index++) {
  45026. runtimeAnimations[index].reset();
  45027. }
  45028. // Reset to original value
  45029. for (index = 0; index < runtimeAnimations.length; index++) {
  45030. var animation = runtimeAnimations[index];
  45031. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  45032. }
  45033. this._localDelayOffset = null;
  45034. this._pausedDelay = null;
  45035. };
  45036. Animatable.prototype.enableBlending = function (blendingSpeed) {
  45037. var runtimeAnimations = this._runtimeAnimations;
  45038. for (var index = 0; index < runtimeAnimations.length; index++) {
  45039. runtimeAnimations[index].animation.enableBlending = true;
  45040. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  45041. }
  45042. };
  45043. Animatable.prototype.disableBlending = function () {
  45044. var runtimeAnimations = this._runtimeAnimations;
  45045. for (var index = 0; index < runtimeAnimations.length; index++) {
  45046. runtimeAnimations[index].animation.enableBlending = false;
  45047. }
  45048. };
  45049. Animatable.prototype.goToFrame = function (frame) {
  45050. var runtimeAnimations = this._runtimeAnimations;
  45051. if (runtimeAnimations[0]) {
  45052. var fps = runtimeAnimations[0].animation.framePerSecond;
  45053. var currentFrame = runtimeAnimations[0].currentFrame;
  45054. var adjustTime = frame - currentFrame;
  45055. var delay = adjustTime * 1000 / fps;
  45056. if (this._localDelayOffset === null) {
  45057. this._localDelayOffset = 0;
  45058. }
  45059. this._localDelayOffset -= delay;
  45060. }
  45061. for (var index = 0; index < runtimeAnimations.length; index++) {
  45062. runtimeAnimations[index].goToFrame(frame);
  45063. }
  45064. };
  45065. Animatable.prototype.pause = function () {
  45066. if (this._paused) {
  45067. return;
  45068. }
  45069. this._paused = true;
  45070. };
  45071. Animatable.prototype.restart = function () {
  45072. this._paused = false;
  45073. };
  45074. Animatable.prototype.stop = function (animationName) {
  45075. if (animationName) {
  45076. var idx = this._scene._activeAnimatables.indexOf(this);
  45077. if (idx > -1) {
  45078. var runtimeAnimations = this._runtimeAnimations;
  45079. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  45080. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  45081. continue;
  45082. }
  45083. runtimeAnimations[index].dispose();
  45084. runtimeAnimations.splice(index, 1);
  45085. }
  45086. if (runtimeAnimations.length == 0) {
  45087. this._scene._activeAnimatables.splice(idx, 1);
  45088. if (this.onAnimationEnd) {
  45089. this.onAnimationEnd();
  45090. }
  45091. }
  45092. }
  45093. }
  45094. else {
  45095. var index = this._scene._activeAnimatables.indexOf(this);
  45096. if (index > -1) {
  45097. this._scene._activeAnimatables.splice(index, 1);
  45098. var runtimeAnimations = this._runtimeAnimations;
  45099. for (var index = 0; index < runtimeAnimations.length; index++) {
  45100. runtimeAnimations[index].dispose();
  45101. }
  45102. if (this.onAnimationEnd) {
  45103. this.onAnimationEnd();
  45104. }
  45105. }
  45106. }
  45107. };
  45108. Animatable.prototype._animate = function (delay) {
  45109. if (this._paused) {
  45110. this.animationStarted = false;
  45111. if (this._pausedDelay === null) {
  45112. this._pausedDelay = delay;
  45113. }
  45114. return true;
  45115. }
  45116. if (this._localDelayOffset === null) {
  45117. this._localDelayOffset = delay;
  45118. this._pausedDelay = null;
  45119. }
  45120. else if (this._pausedDelay !== null) {
  45121. this._localDelayOffset += delay - this._pausedDelay;
  45122. this._pausedDelay = null;
  45123. }
  45124. // Animating
  45125. var running = false;
  45126. var runtimeAnimations = this._runtimeAnimations;
  45127. var index;
  45128. for (index = 0; index < runtimeAnimations.length; index++) {
  45129. var animation = runtimeAnimations[index];
  45130. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  45131. running = running || isRunning;
  45132. }
  45133. this.animationStarted = running;
  45134. if (!running) {
  45135. // Remove from active animatables
  45136. index = this._scene._activeAnimatables.indexOf(this);
  45137. this._scene._activeAnimatables.splice(index, 1);
  45138. // Dispose all runtime animations
  45139. for (index = 0; index < runtimeAnimations.length; index++) {
  45140. runtimeAnimations[index].dispose();
  45141. }
  45142. }
  45143. if (!running && this.onAnimationEnd) {
  45144. this.onAnimationEnd();
  45145. this.onAnimationEnd = null;
  45146. }
  45147. return running;
  45148. };
  45149. return Animatable;
  45150. }());
  45151. BABYLON.Animatable = Animatable;
  45152. })(BABYLON || (BABYLON = {}));
  45153. //# sourceMappingURL=babylon.animatable.js.map
  45154. var BABYLON;
  45155. (function (BABYLON) {
  45156. var EasingFunction = /** @class */ (function () {
  45157. function EasingFunction() {
  45158. // Properties
  45159. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  45160. }
  45161. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  45162. get: function () {
  45163. return EasingFunction._EASINGMODE_EASEIN;
  45164. },
  45165. enumerable: true,
  45166. configurable: true
  45167. });
  45168. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  45169. get: function () {
  45170. return EasingFunction._EASINGMODE_EASEOUT;
  45171. },
  45172. enumerable: true,
  45173. configurable: true
  45174. });
  45175. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  45176. get: function () {
  45177. return EasingFunction._EASINGMODE_EASEINOUT;
  45178. },
  45179. enumerable: true,
  45180. configurable: true
  45181. });
  45182. EasingFunction.prototype.setEasingMode = function (easingMode) {
  45183. var n = Math.min(Math.max(easingMode, 0), 2);
  45184. this._easingMode = n;
  45185. };
  45186. EasingFunction.prototype.getEasingMode = function () {
  45187. return this._easingMode;
  45188. };
  45189. EasingFunction.prototype.easeInCore = function (gradient) {
  45190. throw new Error('You must implement this method');
  45191. };
  45192. EasingFunction.prototype.ease = function (gradient) {
  45193. switch (this._easingMode) {
  45194. case EasingFunction.EASINGMODE_EASEIN:
  45195. return this.easeInCore(gradient);
  45196. case EasingFunction.EASINGMODE_EASEOUT:
  45197. return (1 - this.easeInCore(1 - gradient));
  45198. }
  45199. if (gradient >= 0.5) {
  45200. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  45201. }
  45202. return (this.easeInCore(gradient * 2) * 0.5);
  45203. };
  45204. //Statics
  45205. EasingFunction._EASINGMODE_EASEIN = 0;
  45206. EasingFunction._EASINGMODE_EASEOUT = 1;
  45207. EasingFunction._EASINGMODE_EASEINOUT = 2;
  45208. return EasingFunction;
  45209. }());
  45210. BABYLON.EasingFunction = EasingFunction;
  45211. var CircleEase = /** @class */ (function (_super) {
  45212. __extends(CircleEase, _super);
  45213. function CircleEase() {
  45214. return _super !== null && _super.apply(this, arguments) || this;
  45215. }
  45216. CircleEase.prototype.easeInCore = function (gradient) {
  45217. gradient = Math.max(0, Math.min(1, gradient));
  45218. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  45219. };
  45220. return CircleEase;
  45221. }(EasingFunction));
  45222. BABYLON.CircleEase = CircleEase;
  45223. var BackEase = /** @class */ (function (_super) {
  45224. __extends(BackEase, _super);
  45225. function BackEase(amplitude) {
  45226. if (amplitude === void 0) { amplitude = 1; }
  45227. var _this = _super.call(this) || this;
  45228. _this.amplitude = amplitude;
  45229. return _this;
  45230. }
  45231. BackEase.prototype.easeInCore = function (gradient) {
  45232. var num = Math.max(0, this.amplitude);
  45233. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  45234. };
  45235. return BackEase;
  45236. }(EasingFunction));
  45237. BABYLON.BackEase = BackEase;
  45238. var BounceEase = /** @class */ (function (_super) {
  45239. __extends(BounceEase, _super);
  45240. function BounceEase(bounces, bounciness) {
  45241. if (bounces === void 0) { bounces = 3; }
  45242. if (bounciness === void 0) { bounciness = 2; }
  45243. var _this = _super.call(this) || this;
  45244. _this.bounces = bounces;
  45245. _this.bounciness = bounciness;
  45246. return _this;
  45247. }
  45248. BounceEase.prototype.easeInCore = function (gradient) {
  45249. var y = Math.max(0.0, this.bounces);
  45250. var bounciness = this.bounciness;
  45251. if (bounciness <= 1.0) {
  45252. bounciness = 1.001;
  45253. }
  45254. var num9 = Math.pow(bounciness, y);
  45255. var num5 = 1.0 - bounciness;
  45256. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  45257. var num15 = gradient * num4;
  45258. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  45259. var num3 = Math.floor(num65);
  45260. var num13 = num3 + 1.0;
  45261. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  45262. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  45263. var num7 = (num8 + num12) * 0.5;
  45264. var num6 = gradient - num7;
  45265. var num2 = num7 - num8;
  45266. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  45267. };
  45268. return BounceEase;
  45269. }(EasingFunction));
  45270. BABYLON.BounceEase = BounceEase;
  45271. var CubicEase = /** @class */ (function (_super) {
  45272. __extends(CubicEase, _super);
  45273. function CubicEase() {
  45274. return _super !== null && _super.apply(this, arguments) || this;
  45275. }
  45276. CubicEase.prototype.easeInCore = function (gradient) {
  45277. return (gradient * gradient * gradient);
  45278. };
  45279. return CubicEase;
  45280. }(EasingFunction));
  45281. BABYLON.CubicEase = CubicEase;
  45282. var ElasticEase = /** @class */ (function (_super) {
  45283. __extends(ElasticEase, _super);
  45284. function ElasticEase(oscillations, springiness) {
  45285. if (oscillations === void 0) { oscillations = 3; }
  45286. if (springiness === void 0) { springiness = 3; }
  45287. var _this = _super.call(this) || this;
  45288. _this.oscillations = oscillations;
  45289. _this.springiness = springiness;
  45290. return _this;
  45291. }
  45292. ElasticEase.prototype.easeInCore = function (gradient) {
  45293. var num2;
  45294. var num3 = Math.max(0.0, this.oscillations);
  45295. var num = Math.max(0.0, this.springiness);
  45296. if (num == 0) {
  45297. num2 = gradient;
  45298. }
  45299. else {
  45300. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  45301. }
  45302. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  45303. };
  45304. return ElasticEase;
  45305. }(EasingFunction));
  45306. BABYLON.ElasticEase = ElasticEase;
  45307. var ExponentialEase = /** @class */ (function (_super) {
  45308. __extends(ExponentialEase, _super);
  45309. function ExponentialEase(exponent) {
  45310. if (exponent === void 0) { exponent = 2; }
  45311. var _this = _super.call(this) || this;
  45312. _this.exponent = exponent;
  45313. return _this;
  45314. }
  45315. ExponentialEase.prototype.easeInCore = function (gradient) {
  45316. if (this.exponent <= 0) {
  45317. return gradient;
  45318. }
  45319. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  45320. };
  45321. return ExponentialEase;
  45322. }(EasingFunction));
  45323. BABYLON.ExponentialEase = ExponentialEase;
  45324. var PowerEase = /** @class */ (function (_super) {
  45325. __extends(PowerEase, _super);
  45326. function PowerEase(power) {
  45327. if (power === void 0) { power = 2; }
  45328. var _this = _super.call(this) || this;
  45329. _this.power = power;
  45330. return _this;
  45331. }
  45332. PowerEase.prototype.easeInCore = function (gradient) {
  45333. var y = Math.max(0.0, this.power);
  45334. return Math.pow(gradient, y);
  45335. };
  45336. return PowerEase;
  45337. }(EasingFunction));
  45338. BABYLON.PowerEase = PowerEase;
  45339. var QuadraticEase = /** @class */ (function (_super) {
  45340. __extends(QuadraticEase, _super);
  45341. function QuadraticEase() {
  45342. return _super !== null && _super.apply(this, arguments) || this;
  45343. }
  45344. QuadraticEase.prototype.easeInCore = function (gradient) {
  45345. return (gradient * gradient);
  45346. };
  45347. return QuadraticEase;
  45348. }(EasingFunction));
  45349. BABYLON.QuadraticEase = QuadraticEase;
  45350. var QuarticEase = /** @class */ (function (_super) {
  45351. __extends(QuarticEase, _super);
  45352. function QuarticEase() {
  45353. return _super !== null && _super.apply(this, arguments) || this;
  45354. }
  45355. QuarticEase.prototype.easeInCore = function (gradient) {
  45356. return (gradient * gradient * gradient * gradient);
  45357. };
  45358. return QuarticEase;
  45359. }(EasingFunction));
  45360. BABYLON.QuarticEase = QuarticEase;
  45361. var QuinticEase = /** @class */ (function (_super) {
  45362. __extends(QuinticEase, _super);
  45363. function QuinticEase() {
  45364. return _super !== null && _super.apply(this, arguments) || this;
  45365. }
  45366. QuinticEase.prototype.easeInCore = function (gradient) {
  45367. return (gradient * gradient * gradient * gradient * gradient);
  45368. };
  45369. return QuinticEase;
  45370. }(EasingFunction));
  45371. BABYLON.QuinticEase = QuinticEase;
  45372. var SineEase = /** @class */ (function (_super) {
  45373. __extends(SineEase, _super);
  45374. function SineEase() {
  45375. return _super !== null && _super.apply(this, arguments) || this;
  45376. }
  45377. SineEase.prototype.easeInCore = function (gradient) {
  45378. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  45379. };
  45380. return SineEase;
  45381. }(EasingFunction));
  45382. BABYLON.SineEase = SineEase;
  45383. var BezierCurveEase = /** @class */ (function (_super) {
  45384. __extends(BezierCurveEase, _super);
  45385. function BezierCurveEase(x1, y1, x2, y2) {
  45386. if (x1 === void 0) { x1 = 0; }
  45387. if (y1 === void 0) { y1 = 0; }
  45388. if (x2 === void 0) { x2 = 1; }
  45389. if (y2 === void 0) { y2 = 1; }
  45390. var _this = _super.call(this) || this;
  45391. _this.x1 = x1;
  45392. _this.y1 = y1;
  45393. _this.x2 = x2;
  45394. _this.y2 = y2;
  45395. return _this;
  45396. }
  45397. BezierCurveEase.prototype.easeInCore = function (gradient) {
  45398. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  45399. };
  45400. return BezierCurveEase;
  45401. }(EasingFunction));
  45402. BABYLON.BezierCurveEase = BezierCurveEase;
  45403. })(BABYLON || (BABYLON = {}));
  45404. //# sourceMappingURL=babylon.easing.js.map
  45405. var BABYLON;
  45406. (function (BABYLON) {
  45407. var Condition = /** @class */ (function () {
  45408. function Condition(actionManager) {
  45409. this._actionManager = actionManager;
  45410. }
  45411. Condition.prototype.isValid = function () {
  45412. return true;
  45413. };
  45414. Condition.prototype._getProperty = function (propertyPath) {
  45415. return this._actionManager._getProperty(propertyPath);
  45416. };
  45417. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45418. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45419. };
  45420. Condition.prototype.serialize = function () {
  45421. };
  45422. Condition.prototype._serialize = function (serializedCondition) {
  45423. return {
  45424. type: 2,
  45425. children: [],
  45426. name: serializedCondition.name,
  45427. properties: serializedCondition.properties
  45428. };
  45429. };
  45430. return Condition;
  45431. }());
  45432. BABYLON.Condition = Condition;
  45433. var ValueCondition = /** @class */ (function (_super) {
  45434. __extends(ValueCondition, _super);
  45435. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45436. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45437. var _this = _super.call(this, actionManager) || this;
  45438. _this.propertyPath = propertyPath;
  45439. _this.value = value;
  45440. _this.operator = operator;
  45441. _this._target = target;
  45442. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45443. _this._property = _this._getProperty(_this.propertyPath);
  45444. return _this;
  45445. }
  45446. Object.defineProperty(ValueCondition, "IsEqual", {
  45447. get: function () {
  45448. return ValueCondition._IsEqual;
  45449. },
  45450. enumerable: true,
  45451. configurable: true
  45452. });
  45453. Object.defineProperty(ValueCondition, "IsDifferent", {
  45454. get: function () {
  45455. return ValueCondition._IsDifferent;
  45456. },
  45457. enumerable: true,
  45458. configurable: true
  45459. });
  45460. Object.defineProperty(ValueCondition, "IsGreater", {
  45461. get: function () {
  45462. return ValueCondition._IsGreater;
  45463. },
  45464. enumerable: true,
  45465. configurable: true
  45466. });
  45467. Object.defineProperty(ValueCondition, "IsLesser", {
  45468. get: function () {
  45469. return ValueCondition._IsLesser;
  45470. },
  45471. enumerable: true,
  45472. configurable: true
  45473. });
  45474. // Methods
  45475. ValueCondition.prototype.isValid = function () {
  45476. switch (this.operator) {
  45477. case ValueCondition.IsGreater:
  45478. return this._effectiveTarget[this._property] > this.value;
  45479. case ValueCondition.IsLesser:
  45480. return this._effectiveTarget[this._property] < this.value;
  45481. case ValueCondition.IsEqual:
  45482. case ValueCondition.IsDifferent:
  45483. var check;
  45484. if (this.value.equals) {
  45485. check = this.value.equals(this._effectiveTarget[this._property]);
  45486. }
  45487. else {
  45488. check = this.value === this._effectiveTarget[this._property];
  45489. }
  45490. return this.operator === ValueCondition.IsEqual ? check : !check;
  45491. }
  45492. return false;
  45493. };
  45494. ValueCondition.prototype.serialize = function () {
  45495. return this._serialize({
  45496. name: "ValueCondition",
  45497. properties: [
  45498. BABYLON.Action._GetTargetProperty(this._target),
  45499. { name: "propertyPath", value: this.propertyPath },
  45500. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45501. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45502. ]
  45503. });
  45504. };
  45505. ValueCondition.GetOperatorName = function (operator) {
  45506. switch (operator) {
  45507. case ValueCondition._IsEqual: return "IsEqual";
  45508. case ValueCondition._IsDifferent: return "IsDifferent";
  45509. case ValueCondition._IsGreater: return "IsGreater";
  45510. case ValueCondition._IsLesser: return "IsLesser";
  45511. default: return "";
  45512. }
  45513. };
  45514. // Statics
  45515. ValueCondition._IsEqual = 0;
  45516. ValueCondition._IsDifferent = 1;
  45517. ValueCondition._IsGreater = 2;
  45518. ValueCondition._IsLesser = 3;
  45519. return ValueCondition;
  45520. }(Condition));
  45521. BABYLON.ValueCondition = ValueCondition;
  45522. var PredicateCondition = /** @class */ (function (_super) {
  45523. __extends(PredicateCondition, _super);
  45524. function PredicateCondition(actionManager, predicate) {
  45525. var _this = _super.call(this, actionManager) || this;
  45526. _this.predicate = predicate;
  45527. return _this;
  45528. }
  45529. PredicateCondition.prototype.isValid = function () {
  45530. return this.predicate();
  45531. };
  45532. return PredicateCondition;
  45533. }(Condition));
  45534. BABYLON.PredicateCondition = PredicateCondition;
  45535. var StateCondition = /** @class */ (function (_super) {
  45536. __extends(StateCondition, _super);
  45537. function StateCondition(actionManager, target, value) {
  45538. var _this = _super.call(this, actionManager) || this;
  45539. _this.value = value;
  45540. _this._target = target;
  45541. return _this;
  45542. }
  45543. // Methods
  45544. StateCondition.prototype.isValid = function () {
  45545. return this._target.state === this.value;
  45546. };
  45547. StateCondition.prototype.serialize = function () {
  45548. return this._serialize({
  45549. name: "StateCondition",
  45550. properties: [
  45551. BABYLON.Action._GetTargetProperty(this._target),
  45552. { name: "value", value: this.value }
  45553. ]
  45554. });
  45555. };
  45556. return StateCondition;
  45557. }(Condition));
  45558. BABYLON.StateCondition = StateCondition;
  45559. })(BABYLON || (BABYLON = {}));
  45560. //# sourceMappingURL=babylon.condition.js.map
  45561. var BABYLON;
  45562. (function (BABYLON) {
  45563. var Action = /** @class */ (function () {
  45564. function Action(triggerOptions, condition) {
  45565. this.triggerOptions = triggerOptions;
  45566. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45567. if (triggerOptions.parameter) {
  45568. this.trigger = triggerOptions.trigger;
  45569. this._triggerParameter = triggerOptions.parameter;
  45570. }
  45571. else {
  45572. this.trigger = triggerOptions;
  45573. }
  45574. this._nextActiveAction = this;
  45575. this._condition = condition;
  45576. }
  45577. // Methods
  45578. Action.prototype._prepare = function () {
  45579. };
  45580. Action.prototype.getTriggerParameter = function () {
  45581. return this._triggerParameter;
  45582. };
  45583. Action.prototype._executeCurrent = function (evt) {
  45584. if (this._nextActiveAction._condition) {
  45585. var condition = this._nextActiveAction._condition;
  45586. var currentRenderId = this._actionManager.getScene().getRenderId();
  45587. // We cache the current evaluation for the current frame
  45588. if (condition._evaluationId === currentRenderId) {
  45589. if (!condition._currentResult) {
  45590. return;
  45591. }
  45592. }
  45593. else {
  45594. condition._evaluationId = currentRenderId;
  45595. if (!condition.isValid()) {
  45596. condition._currentResult = false;
  45597. return;
  45598. }
  45599. condition._currentResult = true;
  45600. }
  45601. }
  45602. this.onBeforeExecuteObservable.notifyObservers(this);
  45603. this._nextActiveAction.execute(evt);
  45604. this.skipToNextActiveAction();
  45605. };
  45606. Action.prototype.execute = function (evt) {
  45607. };
  45608. Action.prototype.skipToNextActiveAction = function () {
  45609. if (this._nextActiveAction._child) {
  45610. if (!this._nextActiveAction._child._actionManager) {
  45611. this._nextActiveAction._child._actionManager = this._actionManager;
  45612. }
  45613. this._nextActiveAction = this._nextActiveAction._child;
  45614. }
  45615. else {
  45616. this._nextActiveAction = this;
  45617. }
  45618. };
  45619. Action.prototype.then = function (action) {
  45620. this._child = action;
  45621. action._actionManager = this._actionManager;
  45622. action._prepare();
  45623. return action;
  45624. };
  45625. Action.prototype._getProperty = function (propertyPath) {
  45626. return this._actionManager._getProperty(propertyPath);
  45627. };
  45628. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45629. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45630. };
  45631. Action.prototype.serialize = function (parent) {
  45632. };
  45633. // Called by BABYLON.Action objects in serialize(...). Internal use
  45634. Action.prototype._serialize = function (serializedAction, parent) {
  45635. var serializationObject = {
  45636. type: 1,
  45637. children: [],
  45638. name: serializedAction.name,
  45639. properties: serializedAction.properties || []
  45640. };
  45641. // Serialize child
  45642. if (this._child) {
  45643. this._child.serialize(serializationObject);
  45644. }
  45645. // Check if "this" has a condition
  45646. if (this._condition) {
  45647. var serializedCondition = this._condition.serialize();
  45648. serializedCondition.children.push(serializationObject);
  45649. if (parent) {
  45650. parent.children.push(serializedCondition);
  45651. }
  45652. return serializedCondition;
  45653. }
  45654. if (parent) {
  45655. parent.children.push(serializationObject);
  45656. }
  45657. return serializationObject;
  45658. };
  45659. Action._SerializeValueAsString = function (value) {
  45660. if (typeof value === "number") {
  45661. return value.toString();
  45662. }
  45663. if (typeof value === "boolean") {
  45664. return value ? "true" : "false";
  45665. }
  45666. if (value instanceof BABYLON.Vector2) {
  45667. return value.x + ", " + value.y;
  45668. }
  45669. if (value instanceof BABYLON.Vector3) {
  45670. return value.x + ", " + value.y + ", " + value.z;
  45671. }
  45672. if (value instanceof BABYLON.Color3) {
  45673. return value.r + ", " + value.g + ", " + value.b;
  45674. }
  45675. if (value instanceof BABYLON.Color4) {
  45676. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45677. }
  45678. return value; // string
  45679. };
  45680. Action._GetTargetProperty = function (target) {
  45681. return {
  45682. name: "target",
  45683. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45684. : target instanceof BABYLON.Light ? "LightProperties"
  45685. : target instanceof BABYLON.Camera ? "CameraProperties"
  45686. : "SceneProperties",
  45687. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45688. };
  45689. };
  45690. return Action;
  45691. }());
  45692. BABYLON.Action = Action;
  45693. })(BABYLON || (BABYLON = {}));
  45694. //# sourceMappingURL=babylon.action.js.map
  45695. var BABYLON;
  45696. (function (BABYLON) {
  45697. /**
  45698. * ActionEvent is the event beint sent when an action is triggered.
  45699. */
  45700. var ActionEvent = /** @class */ (function () {
  45701. /**
  45702. * @param source The mesh or sprite that triggered the action.
  45703. * @param pointerX The X mouse cursor position at the time of the event
  45704. * @param pointerY The Y mouse cursor position at the time of the event
  45705. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45706. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45707. */
  45708. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45709. this.source = source;
  45710. this.pointerX = pointerX;
  45711. this.pointerY = pointerY;
  45712. this.meshUnderPointer = meshUnderPointer;
  45713. this.sourceEvent = sourceEvent;
  45714. this.additionalData = additionalData;
  45715. }
  45716. /**
  45717. * Helper function to auto-create an ActionEvent from a source mesh.
  45718. * @param source The source mesh that triggered the event
  45719. * @param evt {Event} The original (browser) event
  45720. */
  45721. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45722. var scene = source.getScene();
  45723. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45724. };
  45725. /**
  45726. * Helper function to auto-create an ActionEvent from a source mesh.
  45727. * @param source The source sprite that triggered the event
  45728. * @param scene Scene associated with the sprite
  45729. * @param evt {Event} The original (browser) event
  45730. */
  45731. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45732. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45733. };
  45734. /**
  45735. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45736. * @param scene the scene where the event occurred
  45737. * @param evt {Event} The original (browser) event
  45738. */
  45739. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45740. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45741. };
  45742. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45743. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45744. };
  45745. return ActionEvent;
  45746. }());
  45747. BABYLON.ActionEvent = ActionEvent;
  45748. /**
  45749. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45750. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45751. */
  45752. var ActionManager = /** @class */ (function () {
  45753. function ActionManager(scene) {
  45754. // Members
  45755. this.actions = new Array();
  45756. this.hoverCursor = '';
  45757. this._scene = scene;
  45758. scene._actionManagers.push(this);
  45759. }
  45760. Object.defineProperty(ActionManager, "NothingTrigger", {
  45761. get: function () {
  45762. return ActionManager._NothingTrigger;
  45763. },
  45764. enumerable: true,
  45765. configurable: true
  45766. });
  45767. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45768. get: function () {
  45769. return ActionManager._OnPickTrigger;
  45770. },
  45771. enumerable: true,
  45772. configurable: true
  45773. });
  45774. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45775. get: function () {
  45776. return ActionManager._OnLeftPickTrigger;
  45777. },
  45778. enumerable: true,
  45779. configurable: true
  45780. });
  45781. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45782. get: function () {
  45783. return ActionManager._OnRightPickTrigger;
  45784. },
  45785. enumerable: true,
  45786. configurable: true
  45787. });
  45788. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45789. get: function () {
  45790. return ActionManager._OnCenterPickTrigger;
  45791. },
  45792. enumerable: true,
  45793. configurable: true
  45794. });
  45795. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45796. get: function () {
  45797. return ActionManager._OnPickDownTrigger;
  45798. },
  45799. enumerable: true,
  45800. configurable: true
  45801. });
  45802. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45803. get: function () {
  45804. return ActionManager._OnDoublePickTrigger;
  45805. },
  45806. enumerable: true,
  45807. configurable: true
  45808. });
  45809. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45810. get: function () {
  45811. return ActionManager._OnPickUpTrigger;
  45812. },
  45813. enumerable: true,
  45814. configurable: true
  45815. });
  45816. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45817. /// This trigger will only be raised if you also declared a OnPickDown
  45818. get: function () {
  45819. return ActionManager._OnPickOutTrigger;
  45820. },
  45821. enumerable: true,
  45822. configurable: true
  45823. });
  45824. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45825. get: function () {
  45826. return ActionManager._OnLongPressTrigger;
  45827. },
  45828. enumerable: true,
  45829. configurable: true
  45830. });
  45831. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45832. get: function () {
  45833. return ActionManager._OnPointerOverTrigger;
  45834. },
  45835. enumerable: true,
  45836. configurable: true
  45837. });
  45838. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45839. get: function () {
  45840. return ActionManager._OnPointerOutTrigger;
  45841. },
  45842. enumerable: true,
  45843. configurable: true
  45844. });
  45845. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45846. get: function () {
  45847. return ActionManager._OnEveryFrameTrigger;
  45848. },
  45849. enumerable: true,
  45850. configurable: true
  45851. });
  45852. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45853. get: function () {
  45854. return ActionManager._OnIntersectionEnterTrigger;
  45855. },
  45856. enumerable: true,
  45857. configurable: true
  45858. });
  45859. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45860. get: function () {
  45861. return ActionManager._OnIntersectionExitTrigger;
  45862. },
  45863. enumerable: true,
  45864. configurable: true
  45865. });
  45866. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45867. get: function () {
  45868. return ActionManager._OnKeyDownTrigger;
  45869. },
  45870. enumerable: true,
  45871. configurable: true
  45872. });
  45873. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45874. get: function () {
  45875. return ActionManager._OnKeyUpTrigger;
  45876. },
  45877. enumerable: true,
  45878. configurable: true
  45879. });
  45880. // Methods
  45881. ActionManager.prototype.dispose = function () {
  45882. var index = this._scene._actionManagers.indexOf(this);
  45883. for (var i = 0; i < this.actions.length; i++) {
  45884. var action = this.actions[i];
  45885. ActionManager.Triggers[action.trigger]--;
  45886. if (ActionManager.Triggers[action.trigger] === 0) {
  45887. delete ActionManager.Triggers[action.trigger];
  45888. }
  45889. }
  45890. if (index > -1) {
  45891. this._scene._actionManagers.splice(index, 1);
  45892. }
  45893. };
  45894. ActionManager.prototype.getScene = function () {
  45895. return this._scene;
  45896. };
  45897. /**
  45898. * Does this action manager handles actions of any of the given triggers
  45899. * @param {number[]} triggers - the triggers to be tested
  45900. * @return {boolean} whether one (or more) of the triggers is handeled
  45901. */
  45902. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45903. for (var index = 0; index < this.actions.length; index++) {
  45904. var action = this.actions[index];
  45905. if (triggers.indexOf(action.trigger) > -1) {
  45906. return true;
  45907. }
  45908. }
  45909. return false;
  45910. };
  45911. /**
  45912. * Does this action manager handles actions of a given trigger
  45913. * @param {number} trigger - the trigger to be tested
  45914. * @return {boolean} whether the trigger is handeled
  45915. */
  45916. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45917. for (var index = 0; index < this.actions.length; index++) {
  45918. var action = this.actions[index];
  45919. if (action.trigger === trigger) {
  45920. return true;
  45921. }
  45922. }
  45923. return false;
  45924. };
  45925. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45926. /**
  45927. * Does this action manager has pointer triggers
  45928. * @return {boolean} whether or not it has pointer triggers
  45929. */
  45930. get: function () {
  45931. for (var index = 0; index < this.actions.length; index++) {
  45932. var action = this.actions[index];
  45933. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45934. return true;
  45935. }
  45936. }
  45937. return false;
  45938. },
  45939. enumerable: true,
  45940. configurable: true
  45941. });
  45942. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45943. /**
  45944. * Does this action manager has pick triggers
  45945. * @return {boolean} whether or not it has pick triggers
  45946. */
  45947. get: function () {
  45948. for (var index = 0; index < this.actions.length; index++) {
  45949. var action = this.actions[index];
  45950. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45951. return true;
  45952. }
  45953. }
  45954. return false;
  45955. },
  45956. enumerable: true,
  45957. configurable: true
  45958. });
  45959. Object.defineProperty(ActionManager, "HasTriggers", {
  45960. /**
  45961. * Does exist one action manager with at least one trigger
  45962. * @return {boolean} whether or not it exists one action manager with one trigger
  45963. **/
  45964. get: function () {
  45965. for (var t in ActionManager.Triggers) {
  45966. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45967. return true;
  45968. }
  45969. }
  45970. return false;
  45971. },
  45972. enumerable: true,
  45973. configurable: true
  45974. });
  45975. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45976. /**
  45977. * Does exist one action manager with at least one pick trigger
  45978. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45979. **/
  45980. get: function () {
  45981. for (var t in ActionManager.Triggers) {
  45982. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45983. var t_int = parseInt(t);
  45984. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45985. return true;
  45986. }
  45987. }
  45988. }
  45989. return false;
  45990. },
  45991. enumerable: true,
  45992. configurable: true
  45993. });
  45994. /**
  45995. * Does exist one action manager that handles actions of a given trigger
  45996. * @param {number} trigger - the trigger to be tested
  45997. * @return {boolean} whether the trigger is handeled by at least one action manager
  45998. **/
  45999. ActionManager.HasSpecificTrigger = function (trigger) {
  46000. for (var t in ActionManager.Triggers) {
  46001. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46002. var t_int = parseInt(t);
  46003. if (t_int === trigger) {
  46004. return true;
  46005. }
  46006. }
  46007. }
  46008. return false;
  46009. };
  46010. /**
  46011. * Registers an action to this action manager
  46012. * @param {BABYLON.Action} action - the action to be registered
  46013. * @return {BABYLON.Action} the action amended (prepared) after registration
  46014. */
  46015. ActionManager.prototype.registerAction = function (action) {
  46016. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46017. if (this.getScene().actionManager !== this) {
  46018. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46019. return null;
  46020. }
  46021. }
  46022. this.actions.push(action);
  46023. if (ActionManager.Triggers[action.trigger]) {
  46024. ActionManager.Triggers[action.trigger]++;
  46025. }
  46026. else {
  46027. ActionManager.Triggers[action.trigger] = 1;
  46028. }
  46029. action._actionManager = this;
  46030. action._prepare();
  46031. return action;
  46032. };
  46033. /**
  46034. * Unregisters an action to this action manager
  46035. * @param action The action to be unregistered
  46036. * @return whether the action has been unregistered
  46037. */
  46038. ActionManager.prototype.unregisterAction = function (action) {
  46039. var index = this.actions.indexOf(action);
  46040. if (index !== -1) {
  46041. this.actions.splice(index, 1);
  46042. ActionManager.Triggers[action.trigger] -= 1;
  46043. if (ActionManager.Triggers[action.trigger] === 0) {
  46044. delete ActionManager.Triggers[action.trigger];
  46045. }
  46046. delete action._actionManager;
  46047. return true;
  46048. }
  46049. return false;
  46050. };
  46051. /**
  46052. * Process a specific trigger
  46053. * @param {number} trigger - the trigger to process
  46054. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46055. */
  46056. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46057. for (var index = 0; index < this.actions.length; index++) {
  46058. var action = this.actions[index];
  46059. if (action.trigger === trigger) {
  46060. if (evt) {
  46061. if (trigger === ActionManager.OnKeyUpTrigger
  46062. || trigger === ActionManager.OnKeyDownTrigger) {
  46063. var parameter = action.getTriggerParameter();
  46064. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46065. if (!parameter.toLowerCase) {
  46066. continue;
  46067. }
  46068. var lowerCase = parameter.toLowerCase();
  46069. if (lowerCase !== evt.sourceEvent.key) {
  46070. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46071. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46072. if (actualkey !== lowerCase) {
  46073. continue;
  46074. }
  46075. }
  46076. }
  46077. }
  46078. }
  46079. action._executeCurrent(evt);
  46080. }
  46081. }
  46082. };
  46083. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46084. var properties = propertyPath.split(".");
  46085. for (var index = 0; index < properties.length - 1; index++) {
  46086. target = target[properties[index]];
  46087. }
  46088. return target;
  46089. };
  46090. ActionManager.prototype._getProperty = function (propertyPath) {
  46091. var properties = propertyPath.split(".");
  46092. return properties[properties.length - 1];
  46093. };
  46094. ActionManager.prototype.serialize = function (name) {
  46095. var root = {
  46096. children: new Array(),
  46097. name: name,
  46098. type: 3,
  46099. properties: new Array() // Empty for root but required
  46100. };
  46101. for (var i = 0; i < this.actions.length; i++) {
  46102. var triggerObject = {
  46103. type: 0,
  46104. children: new Array(),
  46105. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46106. properties: new Array()
  46107. };
  46108. var triggerOptions = this.actions[i].triggerOptions;
  46109. if (triggerOptions && typeof triggerOptions !== "number") {
  46110. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46111. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46112. }
  46113. else {
  46114. var parameter = {};
  46115. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46116. if (triggerOptions.parameter.mesh) {
  46117. parameter._meshId = triggerOptions.parameter.mesh.id;
  46118. }
  46119. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46120. }
  46121. }
  46122. // Serialize child action, recursively
  46123. this.actions[i].serialize(triggerObject);
  46124. // Add serialized trigger
  46125. root.children.push(triggerObject);
  46126. }
  46127. return root;
  46128. };
  46129. ActionManager.Parse = function (parsedActions, object, scene) {
  46130. var actionManager = new ActionManager(scene);
  46131. if (object === null)
  46132. scene.actionManager = actionManager;
  46133. else
  46134. object.actionManager = actionManager;
  46135. // instanciate a new object
  46136. var instanciate = function (name, params) {
  46137. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  46138. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  46139. newInstance.constructor.apply(newInstance, params);
  46140. return newInstance;
  46141. };
  46142. var parseParameter = function (name, value, target, propertyPath) {
  46143. if (propertyPath === null) {
  46144. // String, boolean or float
  46145. var floatValue = parseFloat(value);
  46146. if (value === "true" || value === "false")
  46147. return value === "true";
  46148. else
  46149. return isNaN(floatValue) ? value : floatValue;
  46150. }
  46151. var effectiveTarget = propertyPath.split(".");
  46152. var values = value.split(",");
  46153. // Get effective Target
  46154. for (var i = 0; i < effectiveTarget.length; i++) {
  46155. target = target[effectiveTarget[i]];
  46156. }
  46157. // Return appropriate value with its type
  46158. if (typeof (target) === "boolean")
  46159. return values[0] === "true";
  46160. if (typeof (target) === "string")
  46161. return values[0];
  46162. // Parameters with multiple values such as Vector3 etc.
  46163. var split = new Array();
  46164. for (var i = 0; i < values.length; i++)
  46165. split.push(parseFloat(values[i]));
  46166. if (target instanceof BABYLON.Vector3)
  46167. return BABYLON.Vector3.FromArray(split);
  46168. if (target instanceof BABYLON.Vector4)
  46169. return BABYLON.Vector4.FromArray(split);
  46170. if (target instanceof BABYLON.Color3)
  46171. return BABYLON.Color3.FromArray(split);
  46172. if (target instanceof BABYLON.Color4)
  46173. return BABYLON.Color4.FromArray(split);
  46174. return parseFloat(values[0]);
  46175. };
  46176. // traverse graph per trigger
  46177. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46178. if (combineArray === void 0) { combineArray = null; }
  46179. if (parsedAction.detached)
  46180. return;
  46181. var parameters = new Array();
  46182. var target = null;
  46183. var propertyPath = null;
  46184. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46185. // Parameters
  46186. if (parsedAction.type === 2)
  46187. parameters.push(actionManager);
  46188. else
  46189. parameters.push(trigger);
  46190. if (combine) {
  46191. var actions = new Array();
  46192. for (var j = 0; j < parsedAction.combine.length; j++) {
  46193. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46194. }
  46195. parameters.push(actions);
  46196. }
  46197. else {
  46198. for (var i = 0; i < parsedAction.properties.length; i++) {
  46199. var value = parsedAction.properties[i].value;
  46200. var name = parsedAction.properties[i].name;
  46201. var targetType = parsedAction.properties[i].targetType;
  46202. if (name === "target")
  46203. if (targetType !== null && targetType === "SceneProperties")
  46204. value = target = scene;
  46205. else
  46206. value = target = scene.getNodeByName(value);
  46207. else if (name === "parent")
  46208. value = scene.getNodeByName(value);
  46209. else if (name === "sound")
  46210. value = scene.getSoundByName(value);
  46211. else if (name !== "propertyPath") {
  46212. if (parsedAction.type === 2 && name === "operator")
  46213. value = BABYLON.ValueCondition[value];
  46214. else
  46215. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46216. }
  46217. else {
  46218. propertyPath = value;
  46219. }
  46220. parameters.push(value);
  46221. }
  46222. }
  46223. if (combineArray === null) {
  46224. parameters.push(condition);
  46225. }
  46226. else {
  46227. parameters.push(null);
  46228. }
  46229. // If interpolate value action
  46230. if (parsedAction.name === "InterpolateValueAction") {
  46231. var param = parameters[parameters.length - 2];
  46232. parameters[parameters.length - 1] = param;
  46233. parameters[parameters.length - 2] = condition;
  46234. }
  46235. // Action or condition(s) and not CombineAction
  46236. var newAction = instanciate(parsedAction.name, parameters);
  46237. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46238. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46239. if (action)
  46240. action.then(nothing);
  46241. else
  46242. actionManager.registerAction(nothing);
  46243. action = nothing;
  46244. }
  46245. if (combineArray === null) {
  46246. if (newAction instanceof BABYLON.Condition) {
  46247. condition = newAction;
  46248. newAction = action;
  46249. }
  46250. else {
  46251. condition = null;
  46252. if (action)
  46253. action.then(newAction);
  46254. else
  46255. actionManager.registerAction(newAction);
  46256. }
  46257. }
  46258. else {
  46259. combineArray.push(newAction);
  46260. }
  46261. for (var i = 0; i < parsedAction.children.length; i++)
  46262. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46263. };
  46264. // triggers
  46265. for (var i = 0; i < parsedActions.children.length; i++) {
  46266. var triggerParams;
  46267. var trigger = parsedActions.children[i];
  46268. if (trigger.properties.length > 0) {
  46269. var param = trigger.properties[0].value;
  46270. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46271. if (value._meshId) {
  46272. value.mesh = scene.getMeshByID(value._meshId);
  46273. }
  46274. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  46275. }
  46276. else
  46277. triggerParams = ActionManager[trigger.name];
  46278. for (var j = 0; j < trigger.children.length; j++) {
  46279. if (!trigger.detached)
  46280. traverse(trigger.children[j], triggerParams, null, null);
  46281. }
  46282. }
  46283. };
  46284. ActionManager.GetTriggerName = function (trigger) {
  46285. switch (trigger) {
  46286. case 0: return "NothingTrigger";
  46287. case 1: return "OnPickTrigger";
  46288. case 2: return "OnLeftPickTrigger";
  46289. case 3: return "OnRightPickTrigger";
  46290. case 4: return "OnCenterPickTrigger";
  46291. case 5: return "OnPickDownTrigger";
  46292. case 6: return "OnPickUpTrigger";
  46293. case 7: return "OnLongPressTrigger";
  46294. case 8: return "OnPointerOverTrigger";
  46295. case 9: return "OnPointerOutTrigger";
  46296. case 10: return "OnEveryFrameTrigger";
  46297. case 11: return "OnIntersectionEnterTrigger";
  46298. case 12: return "OnIntersectionExitTrigger";
  46299. case 13: return "OnKeyDownTrigger";
  46300. case 14: return "OnKeyUpTrigger";
  46301. case 15: return "OnPickOutTrigger";
  46302. default: return "";
  46303. }
  46304. };
  46305. // Statics
  46306. ActionManager._NothingTrigger = 0;
  46307. ActionManager._OnPickTrigger = 1;
  46308. ActionManager._OnLeftPickTrigger = 2;
  46309. ActionManager._OnRightPickTrigger = 3;
  46310. ActionManager._OnCenterPickTrigger = 4;
  46311. ActionManager._OnPickDownTrigger = 5;
  46312. ActionManager._OnDoublePickTrigger = 6;
  46313. ActionManager._OnPickUpTrigger = 7;
  46314. ActionManager._OnLongPressTrigger = 8;
  46315. ActionManager._OnPointerOverTrigger = 9;
  46316. ActionManager._OnPointerOutTrigger = 10;
  46317. ActionManager._OnEveryFrameTrigger = 11;
  46318. ActionManager._OnIntersectionEnterTrigger = 12;
  46319. ActionManager._OnIntersectionExitTrigger = 13;
  46320. ActionManager._OnKeyDownTrigger = 14;
  46321. ActionManager._OnKeyUpTrigger = 15;
  46322. ActionManager._OnPickOutTrigger = 16;
  46323. ActionManager.Triggers = {};
  46324. return ActionManager;
  46325. }());
  46326. BABYLON.ActionManager = ActionManager;
  46327. })(BABYLON || (BABYLON = {}));
  46328. //# sourceMappingURL=babylon.actionManager.js.map
  46329. var BABYLON;
  46330. (function (BABYLON) {
  46331. var InterpolateValueAction = /** @class */ (function (_super) {
  46332. __extends(InterpolateValueAction, _super);
  46333. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46334. if (duration === void 0) { duration = 1000; }
  46335. var _this = _super.call(this, triggerOptions, condition) || this;
  46336. _this.propertyPath = propertyPath;
  46337. _this.value = value;
  46338. _this.duration = duration;
  46339. _this.stopOtherAnimations = stopOtherAnimations;
  46340. _this.onInterpolationDone = onInterpolationDone;
  46341. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  46342. _this._target = _this._effectiveTarget = target;
  46343. return _this;
  46344. }
  46345. InterpolateValueAction.prototype._prepare = function () {
  46346. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46347. this._property = this._getProperty(this.propertyPath);
  46348. };
  46349. InterpolateValueAction.prototype.execute = function () {
  46350. var _this = this;
  46351. var scene = this._actionManager.getScene();
  46352. var keys = [
  46353. {
  46354. frame: 0,
  46355. value: this._effectiveTarget[this._property]
  46356. }, {
  46357. frame: 100,
  46358. value: this.value
  46359. }
  46360. ];
  46361. var dataType;
  46362. if (typeof this.value === "number") {
  46363. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46364. }
  46365. else if (this.value instanceof BABYLON.Color3) {
  46366. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46367. }
  46368. else if (this.value instanceof BABYLON.Vector3) {
  46369. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46370. }
  46371. else if (this.value instanceof BABYLON.Matrix) {
  46372. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46373. }
  46374. else if (this.value instanceof BABYLON.Quaternion) {
  46375. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46376. }
  46377. else {
  46378. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46379. return;
  46380. }
  46381. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46382. animation.setKeys(keys);
  46383. if (this.stopOtherAnimations) {
  46384. scene.stopAnimation(this._effectiveTarget);
  46385. }
  46386. var wrapper = function () {
  46387. _this.onInterpolationDoneObservable.notifyObservers(_this);
  46388. if (_this.onInterpolationDone) {
  46389. _this.onInterpolationDone();
  46390. }
  46391. };
  46392. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  46393. };
  46394. InterpolateValueAction.prototype.serialize = function (parent) {
  46395. return _super.prototype._serialize.call(this, {
  46396. name: "InterpolateValueAction",
  46397. properties: [
  46398. BABYLON.Action._GetTargetProperty(this._target),
  46399. { name: "propertyPath", value: this.propertyPath },
  46400. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46401. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46402. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46403. ]
  46404. }, parent);
  46405. };
  46406. return InterpolateValueAction;
  46407. }(BABYLON.Action));
  46408. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46409. })(BABYLON || (BABYLON = {}));
  46410. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46411. var BABYLON;
  46412. (function (BABYLON) {
  46413. var SwitchBooleanAction = /** @class */ (function (_super) {
  46414. __extends(SwitchBooleanAction, _super);
  46415. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46416. var _this = _super.call(this, triggerOptions, condition) || this;
  46417. _this.propertyPath = propertyPath;
  46418. _this._target = _this._effectiveTarget = target;
  46419. return _this;
  46420. }
  46421. SwitchBooleanAction.prototype._prepare = function () {
  46422. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46423. this._property = this._getProperty(this.propertyPath);
  46424. };
  46425. SwitchBooleanAction.prototype.execute = function () {
  46426. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46427. };
  46428. SwitchBooleanAction.prototype.serialize = function (parent) {
  46429. return _super.prototype._serialize.call(this, {
  46430. name: "SwitchBooleanAction",
  46431. properties: [
  46432. BABYLON.Action._GetTargetProperty(this._target),
  46433. { name: "propertyPath", value: this.propertyPath }
  46434. ]
  46435. }, parent);
  46436. };
  46437. return SwitchBooleanAction;
  46438. }(BABYLON.Action));
  46439. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46440. var SetStateAction = /** @class */ (function (_super) {
  46441. __extends(SetStateAction, _super);
  46442. function SetStateAction(triggerOptions, target, value, condition) {
  46443. var _this = _super.call(this, triggerOptions, condition) || this;
  46444. _this.value = value;
  46445. _this._target = target;
  46446. return _this;
  46447. }
  46448. SetStateAction.prototype.execute = function () {
  46449. this._target.state = this.value;
  46450. };
  46451. SetStateAction.prototype.serialize = function (parent) {
  46452. return _super.prototype._serialize.call(this, {
  46453. name: "SetStateAction",
  46454. properties: [
  46455. BABYLON.Action._GetTargetProperty(this._target),
  46456. { name: "value", value: this.value }
  46457. ]
  46458. }, parent);
  46459. };
  46460. return SetStateAction;
  46461. }(BABYLON.Action));
  46462. BABYLON.SetStateAction = SetStateAction;
  46463. var SetValueAction = /** @class */ (function (_super) {
  46464. __extends(SetValueAction, _super);
  46465. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46466. var _this = _super.call(this, triggerOptions, condition) || this;
  46467. _this.propertyPath = propertyPath;
  46468. _this.value = value;
  46469. _this._target = _this._effectiveTarget = target;
  46470. return _this;
  46471. }
  46472. SetValueAction.prototype._prepare = function () {
  46473. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46474. this._property = this._getProperty(this.propertyPath);
  46475. };
  46476. SetValueAction.prototype.execute = function () {
  46477. this._effectiveTarget[this._property] = this.value;
  46478. if (this._target.markAsDirty) {
  46479. this._target.markAsDirty(this._property);
  46480. }
  46481. };
  46482. SetValueAction.prototype.serialize = function (parent) {
  46483. return _super.prototype._serialize.call(this, {
  46484. name: "SetValueAction",
  46485. properties: [
  46486. BABYLON.Action._GetTargetProperty(this._target),
  46487. { name: "propertyPath", value: this.propertyPath },
  46488. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46489. ]
  46490. }, parent);
  46491. };
  46492. return SetValueAction;
  46493. }(BABYLON.Action));
  46494. BABYLON.SetValueAction = SetValueAction;
  46495. var IncrementValueAction = /** @class */ (function (_super) {
  46496. __extends(IncrementValueAction, _super);
  46497. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46498. var _this = _super.call(this, triggerOptions, condition) || this;
  46499. _this.propertyPath = propertyPath;
  46500. _this.value = value;
  46501. _this._target = _this._effectiveTarget = target;
  46502. return _this;
  46503. }
  46504. IncrementValueAction.prototype._prepare = function () {
  46505. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46506. this._property = this._getProperty(this.propertyPath);
  46507. if (typeof this._effectiveTarget[this._property] !== "number") {
  46508. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46509. }
  46510. };
  46511. IncrementValueAction.prototype.execute = function () {
  46512. this._effectiveTarget[this._property] += this.value;
  46513. if (this._target.markAsDirty) {
  46514. this._target.markAsDirty(this._property);
  46515. }
  46516. };
  46517. IncrementValueAction.prototype.serialize = function (parent) {
  46518. return _super.prototype._serialize.call(this, {
  46519. name: "IncrementValueAction",
  46520. properties: [
  46521. BABYLON.Action._GetTargetProperty(this._target),
  46522. { name: "propertyPath", value: this.propertyPath },
  46523. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46524. ]
  46525. }, parent);
  46526. };
  46527. return IncrementValueAction;
  46528. }(BABYLON.Action));
  46529. BABYLON.IncrementValueAction = IncrementValueAction;
  46530. var PlayAnimationAction = /** @class */ (function (_super) {
  46531. __extends(PlayAnimationAction, _super);
  46532. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46533. var _this = _super.call(this, triggerOptions, condition) || this;
  46534. _this.from = from;
  46535. _this.to = to;
  46536. _this.loop = loop;
  46537. _this._target = target;
  46538. return _this;
  46539. }
  46540. PlayAnimationAction.prototype._prepare = function () {
  46541. };
  46542. PlayAnimationAction.prototype.execute = function () {
  46543. var scene = this._actionManager.getScene();
  46544. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46545. };
  46546. PlayAnimationAction.prototype.serialize = function (parent) {
  46547. return _super.prototype._serialize.call(this, {
  46548. name: "PlayAnimationAction",
  46549. properties: [
  46550. BABYLON.Action._GetTargetProperty(this._target),
  46551. { name: "from", value: String(this.from) },
  46552. { name: "to", value: String(this.to) },
  46553. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46554. ]
  46555. }, parent);
  46556. };
  46557. return PlayAnimationAction;
  46558. }(BABYLON.Action));
  46559. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46560. var StopAnimationAction = /** @class */ (function (_super) {
  46561. __extends(StopAnimationAction, _super);
  46562. function StopAnimationAction(triggerOptions, target, condition) {
  46563. var _this = _super.call(this, triggerOptions, condition) || this;
  46564. _this._target = target;
  46565. return _this;
  46566. }
  46567. StopAnimationAction.prototype._prepare = function () {
  46568. };
  46569. StopAnimationAction.prototype.execute = function () {
  46570. var scene = this._actionManager.getScene();
  46571. scene.stopAnimation(this._target);
  46572. };
  46573. StopAnimationAction.prototype.serialize = function (parent) {
  46574. return _super.prototype._serialize.call(this, {
  46575. name: "StopAnimationAction",
  46576. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46577. }, parent);
  46578. };
  46579. return StopAnimationAction;
  46580. }(BABYLON.Action));
  46581. BABYLON.StopAnimationAction = StopAnimationAction;
  46582. var DoNothingAction = /** @class */ (function (_super) {
  46583. __extends(DoNothingAction, _super);
  46584. function DoNothingAction(triggerOptions, condition) {
  46585. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46586. return _super.call(this, triggerOptions, condition) || this;
  46587. }
  46588. DoNothingAction.prototype.execute = function () {
  46589. };
  46590. DoNothingAction.prototype.serialize = function (parent) {
  46591. return _super.prototype._serialize.call(this, {
  46592. name: "DoNothingAction",
  46593. properties: []
  46594. }, parent);
  46595. };
  46596. return DoNothingAction;
  46597. }(BABYLON.Action));
  46598. BABYLON.DoNothingAction = DoNothingAction;
  46599. var CombineAction = /** @class */ (function (_super) {
  46600. __extends(CombineAction, _super);
  46601. function CombineAction(triggerOptions, children, condition) {
  46602. var _this = _super.call(this, triggerOptions, condition) || this;
  46603. _this.children = children;
  46604. return _this;
  46605. }
  46606. CombineAction.prototype._prepare = function () {
  46607. for (var index = 0; index < this.children.length; index++) {
  46608. this.children[index]._actionManager = this._actionManager;
  46609. this.children[index]._prepare();
  46610. }
  46611. };
  46612. CombineAction.prototype.execute = function (evt) {
  46613. for (var index = 0; index < this.children.length; index++) {
  46614. this.children[index].execute(evt);
  46615. }
  46616. };
  46617. CombineAction.prototype.serialize = function (parent) {
  46618. var serializationObject = _super.prototype._serialize.call(this, {
  46619. name: "CombineAction",
  46620. properties: [],
  46621. combine: []
  46622. }, parent);
  46623. for (var i = 0; i < this.children.length; i++) {
  46624. serializationObject.combine.push(this.children[i].serialize(null));
  46625. }
  46626. return serializationObject;
  46627. };
  46628. return CombineAction;
  46629. }(BABYLON.Action));
  46630. BABYLON.CombineAction = CombineAction;
  46631. var ExecuteCodeAction = /** @class */ (function (_super) {
  46632. __extends(ExecuteCodeAction, _super);
  46633. function ExecuteCodeAction(triggerOptions, func, condition) {
  46634. var _this = _super.call(this, triggerOptions, condition) || this;
  46635. _this.func = func;
  46636. return _this;
  46637. }
  46638. ExecuteCodeAction.prototype.execute = function (evt) {
  46639. this.func(evt);
  46640. };
  46641. return ExecuteCodeAction;
  46642. }(BABYLON.Action));
  46643. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46644. var SetParentAction = /** @class */ (function (_super) {
  46645. __extends(SetParentAction, _super);
  46646. function SetParentAction(triggerOptions, target, parent, condition) {
  46647. var _this = _super.call(this, triggerOptions, condition) || this;
  46648. _this._target = target;
  46649. _this._parent = parent;
  46650. return _this;
  46651. }
  46652. SetParentAction.prototype._prepare = function () {
  46653. };
  46654. SetParentAction.prototype.execute = function () {
  46655. if (this._target.parent === this._parent) {
  46656. return;
  46657. }
  46658. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46659. invertParentWorldMatrix.invert();
  46660. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46661. this._target.parent = this._parent;
  46662. };
  46663. SetParentAction.prototype.serialize = function (parent) {
  46664. return _super.prototype._serialize.call(this, {
  46665. name: "SetParentAction",
  46666. properties: [
  46667. BABYLON.Action._GetTargetProperty(this._target),
  46668. BABYLON.Action._GetTargetProperty(this._parent),
  46669. ]
  46670. }, parent);
  46671. };
  46672. return SetParentAction;
  46673. }(BABYLON.Action));
  46674. BABYLON.SetParentAction = SetParentAction;
  46675. var PlaySoundAction = /** @class */ (function (_super) {
  46676. __extends(PlaySoundAction, _super);
  46677. function PlaySoundAction(triggerOptions, sound, condition) {
  46678. var _this = _super.call(this, triggerOptions, condition) || this;
  46679. _this._sound = sound;
  46680. return _this;
  46681. }
  46682. PlaySoundAction.prototype._prepare = function () {
  46683. };
  46684. PlaySoundAction.prototype.execute = function () {
  46685. if (this._sound !== undefined)
  46686. this._sound.play();
  46687. };
  46688. PlaySoundAction.prototype.serialize = function (parent) {
  46689. return _super.prototype._serialize.call(this, {
  46690. name: "PlaySoundAction",
  46691. properties: [{ name: "sound", value: this._sound.name }]
  46692. }, parent);
  46693. };
  46694. return PlaySoundAction;
  46695. }(BABYLON.Action));
  46696. BABYLON.PlaySoundAction = PlaySoundAction;
  46697. var StopSoundAction = /** @class */ (function (_super) {
  46698. __extends(StopSoundAction, _super);
  46699. function StopSoundAction(triggerOptions, sound, condition) {
  46700. var _this = _super.call(this, triggerOptions, condition) || this;
  46701. _this._sound = sound;
  46702. return _this;
  46703. }
  46704. StopSoundAction.prototype._prepare = function () {
  46705. };
  46706. StopSoundAction.prototype.execute = function () {
  46707. if (this._sound !== undefined)
  46708. this._sound.stop();
  46709. };
  46710. StopSoundAction.prototype.serialize = function (parent) {
  46711. return _super.prototype._serialize.call(this, {
  46712. name: "StopSoundAction",
  46713. properties: [{ name: "sound", value: this._sound.name }]
  46714. }, parent);
  46715. };
  46716. return StopSoundAction;
  46717. }(BABYLON.Action));
  46718. BABYLON.StopSoundAction = StopSoundAction;
  46719. })(BABYLON || (BABYLON = {}));
  46720. //# sourceMappingURL=babylon.directActions.js.map
  46721. var BABYLON;
  46722. (function (BABYLON) {
  46723. var SpriteManager = /** @class */ (function () {
  46724. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46725. if (epsilon === void 0) { epsilon = 0.01; }
  46726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46727. this.name = name;
  46728. this.sprites = new Array();
  46729. this.renderingGroupId = 0;
  46730. this.layerMask = 0x0FFFFFFF;
  46731. this.fogEnabled = true;
  46732. this.isPickable = false;
  46733. /**
  46734. * An event triggered when the manager is disposed.
  46735. * @type {BABYLON.Observable}
  46736. */
  46737. this.onDisposeObservable = new BABYLON.Observable();
  46738. this._vertexBuffers = {};
  46739. this._capacity = capacity;
  46740. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46741. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46742. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46743. if (cellSize.width && cellSize.height) {
  46744. this.cellWidth = cellSize.width;
  46745. this.cellHeight = cellSize.height;
  46746. }
  46747. else if (cellSize !== undefined) {
  46748. this.cellWidth = cellSize;
  46749. this.cellHeight = cellSize;
  46750. }
  46751. else {
  46752. return;
  46753. }
  46754. this._epsilon = epsilon;
  46755. this._scene = scene;
  46756. this._scene.spriteManagers.push(this);
  46757. var indices = [];
  46758. var index = 0;
  46759. for (var count = 0; count < capacity; count++) {
  46760. indices.push(index);
  46761. indices.push(index + 1);
  46762. indices.push(index + 2);
  46763. indices.push(index);
  46764. indices.push(index + 2);
  46765. indices.push(index + 3);
  46766. index += 4;
  46767. }
  46768. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46769. // VBO
  46770. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  46771. this._vertexData = new Float32Array(capacity * 16 * 4);
  46772. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  46773. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  46774. var options = this._buffer.createVertexBuffer("options", 4, 4);
  46775. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  46776. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  46777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46778. this._vertexBuffers["options"] = options;
  46779. this._vertexBuffers["cellInfo"] = cellInfo;
  46780. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46781. // Effects
  46782. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  46783. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  46784. }
  46785. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  46786. set: function (callback) {
  46787. if (this._onDisposeObserver) {
  46788. this.onDisposeObservable.remove(this._onDisposeObserver);
  46789. }
  46790. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46791. },
  46792. enumerable: true,
  46793. configurable: true
  46794. });
  46795. Object.defineProperty(SpriteManager.prototype, "texture", {
  46796. get: function () {
  46797. return this._spriteTexture;
  46798. },
  46799. set: function (value) {
  46800. this._spriteTexture = value;
  46801. },
  46802. enumerable: true,
  46803. configurable: true
  46804. });
  46805. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  46806. var arrayOffset = index * 16;
  46807. if (offsetX === 0)
  46808. offsetX = this._epsilon;
  46809. else if (offsetX === 1)
  46810. offsetX = 1 - this._epsilon;
  46811. if (offsetY === 0)
  46812. offsetY = this._epsilon;
  46813. else if (offsetY === 1)
  46814. offsetY = 1 - this._epsilon;
  46815. this._vertexData[arrayOffset] = sprite.position.x;
  46816. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46817. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46818. this._vertexData[arrayOffset + 3] = sprite.angle;
  46819. this._vertexData[arrayOffset + 4] = sprite.width;
  46820. this._vertexData[arrayOffset + 5] = sprite.height;
  46821. this._vertexData[arrayOffset + 6] = offsetX;
  46822. this._vertexData[arrayOffset + 7] = offsetY;
  46823. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46824. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46825. var offset = (sprite.cellIndex / rowSize) >> 0;
  46826. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46827. this._vertexData[arrayOffset + 11] = offset;
  46828. // Color
  46829. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46830. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46831. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46832. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46833. };
  46834. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46835. var count = Math.min(this._capacity, this.sprites.length);
  46836. var min = BABYLON.Vector3.Zero();
  46837. var max = BABYLON.Vector3.Zero();
  46838. var distance = Number.MAX_VALUE;
  46839. var currentSprite = null;
  46840. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46841. var cameraView = camera.getViewMatrix();
  46842. for (var index = 0; index < count; index++) {
  46843. var sprite = this.sprites[index];
  46844. if (!sprite) {
  46845. continue;
  46846. }
  46847. if (predicate) {
  46848. if (!predicate(sprite)) {
  46849. continue;
  46850. }
  46851. }
  46852. else if (!sprite.isPickable) {
  46853. continue;
  46854. }
  46855. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46856. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46857. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46858. if (ray.intersectsBoxMinMax(min, max)) {
  46859. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46860. if (distance > currentDistance) {
  46861. distance = currentDistance;
  46862. currentSprite = sprite;
  46863. if (fastCheck) {
  46864. break;
  46865. }
  46866. }
  46867. }
  46868. }
  46869. if (currentSprite) {
  46870. var result = new BABYLON.PickingInfo();
  46871. result.hit = true;
  46872. result.pickedSprite = currentSprite;
  46873. result.distance = distance;
  46874. return result;
  46875. }
  46876. return null;
  46877. };
  46878. SpriteManager.prototype.render = function () {
  46879. // Check
  46880. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46881. return;
  46882. var engine = this._scene.getEngine();
  46883. var baseSize = this._spriteTexture.getBaseSize();
  46884. // Sprites
  46885. var deltaTime = engine.getDeltaTime();
  46886. var max = Math.min(this._capacity, this.sprites.length);
  46887. var rowSize = baseSize.width / this.cellWidth;
  46888. var offset = 0;
  46889. for (var index = 0; index < max; index++) {
  46890. var sprite = this.sprites[index];
  46891. if (!sprite) {
  46892. continue;
  46893. }
  46894. sprite._animate(deltaTime);
  46895. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46896. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46897. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46898. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46899. }
  46900. this._buffer.update(this._vertexData);
  46901. // Render
  46902. var effect = this._effectBase;
  46903. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46904. effect = this._effectFog;
  46905. }
  46906. engine.enableEffect(effect);
  46907. var viewMatrix = this._scene.getViewMatrix();
  46908. effect.setTexture("diffuseSampler", this._spriteTexture);
  46909. effect.setMatrix("view", viewMatrix);
  46910. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46911. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46912. // Fog
  46913. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46914. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46915. effect.setColor3("vFogColor", this._scene.fogColor);
  46916. }
  46917. // VBOs
  46918. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46919. // Draw order
  46920. engine.setDepthFunctionToLessOrEqual();
  46921. effect.setBool("alphaTest", true);
  46922. engine.setColorWrite(false);
  46923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46924. engine.setColorWrite(true);
  46925. effect.setBool("alphaTest", false);
  46926. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46927. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46929. };
  46930. SpriteManager.prototype.dispose = function () {
  46931. if (this._buffer) {
  46932. this._buffer.dispose();
  46933. this._buffer = null;
  46934. }
  46935. if (this._indexBuffer) {
  46936. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46937. this._indexBuffer = null;
  46938. }
  46939. if (this._spriteTexture) {
  46940. this._spriteTexture.dispose();
  46941. this._spriteTexture = null;
  46942. }
  46943. // Remove from scene
  46944. var index = this._scene.spriteManagers.indexOf(this);
  46945. this._scene.spriteManagers.splice(index, 1);
  46946. // Callback
  46947. this.onDisposeObservable.notifyObservers(this);
  46948. this.onDisposeObservable.clear();
  46949. };
  46950. return SpriteManager;
  46951. }());
  46952. BABYLON.SpriteManager = SpriteManager;
  46953. })(BABYLON || (BABYLON = {}));
  46954. //# sourceMappingURL=babylon.spriteManager.js.map
  46955. var BABYLON;
  46956. (function (BABYLON) {
  46957. var Sprite = /** @class */ (function () {
  46958. function Sprite(name, manager) {
  46959. this.name = name;
  46960. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46961. this.width = 1.0;
  46962. this.height = 1.0;
  46963. this.angle = 0;
  46964. this.cellIndex = 0;
  46965. this.invertU = 0;
  46966. this.invertV = 0;
  46967. this.animations = new Array();
  46968. this.isPickable = false;
  46969. this._animationStarted = false;
  46970. this._loopAnimation = false;
  46971. this._fromIndex = 0;
  46972. this._toIndex = 0;
  46973. this._delay = 0;
  46974. this._direction = 1;
  46975. this._time = 0;
  46976. this._manager = manager;
  46977. this._manager.sprites.push(this);
  46978. this.position = BABYLON.Vector3.Zero();
  46979. }
  46980. Object.defineProperty(Sprite.prototype, "size", {
  46981. get: function () {
  46982. return this.width;
  46983. },
  46984. set: function (value) {
  46985. this.width = value;
  46986. this.height = value;
  46987. },
  46988. enumerable: true,
  46989. configurable: true
  46990. });
  46991. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46992. this._fromIndex = from;
  46993. this._toIndex = to;
  46994. this._loopAnimation = loop;
  46995. this._delay = delay;
  46996. this._animationStarted = true;
  46997. this._direction = from < to ? 1 : -1;
  46998. this.cellIndex = from;
  46999. this._time = 0;
  47000. this._onAnimationEnd = onAnimationEnd;
  47001. };
  47002. Sprite.prototype.stopAnimation = function () {
  47003. this._animationStarted = false;
  47004. };
  47005. Sprite.prototype._animate = function (deltaTime) {
  47006. if (!this._animationStarted)
  47007. return;
  47008. this._time += deltaTime;
  47009. if (this._time > this._delay) {
  47010. this._time = this._time % this._delay;
  47011. this.cellIndex += this._direction;
  47012. if (this.cellIndex > this._toIndex) {
  47013. if (this._loopAnimation) {
  47014. this.cellIndex = this._fromIndex;
  47015. }
  47016. else {
  47017. this.cellIndex = this._toIndex;
  47018. this._animationStarted = false;
  47019. if (this._onAnimationEnd) {
  47020. this._onAnimationEnd();
  47021. }
  47022. if (this.disposeWhenFinishedAnimating) {
  47023. this.dispose();
  47024. }
  47025. }
  47026. }
  47027. }
  47028. };
  47029. Sprite.prototype.dispose = function () {
  47030. for (var i = 0; i < this._manager.sprites.length; i++) {
  47031. if (this._manager.sprites[i] == this) {
  47032. this._manager.sprites.splice(i, 1);
  47033. }
  47034. }
  47035. };
  47036. return Sprite;
  47037. }());
  47038. BABYLON.Sprite = Sprite;
  47039. })(BABYLON || (BABYLON = {}));
  47040. //# sourceMappingURL=babylon.sprite.js.map
  47041. var BABYLON;
  47042. (function (BABYLON) {
  47043. var IntersectionInfo = /** @class */ (function () {
  47044. function IntersectionInfo(bu, bv, distance) {
  47045. this.bu = bu;
  47046. this.bv = bv;
  47047. this.distance = distance;
  47048. this.faceId = 0;
  47049. this.subMeshId = 0;
  47050. }
  47051. return IntersectionInfo;
  47052. }());
  47053. BABYLON.IntersectionInfo = IntersectionInfo;
  47054. var PickingInfo = /** @class */ (function () {
  47055. function PickingInfo() {
  47056. this.hit = false;
  47057. this.distance = 0;
  47058. this.pickedPoint = null;
  47059. this.pickedMesh = null;
  47060. this.bu = 0;
  47061. this.bv = 0;
  47062. this.faceId = -1;
  47063. this.subMeshId = 0;
  47064. this.pickedSprite = null;
  47065. }
  47066. // Methods
  47067. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  47068. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  47069. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  47070. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  47071. return null;
  47072. }
  47073. var indices = this.pickedMesh.getIndices();
  47074. if (!indices) {
  47075. return null;
  47076. }
  47077. var result;
  47078. if (useVerticesNormals) {
  47079. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47080. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  47081. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  47082. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  47083. normal0 = normal0.scale(this.bu);
  47084. normal1 = normal1.scale(this.bv);
  47085. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  47086. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  47087. }
  47088. else {
  47089. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47090. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  47091. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  47092. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  47093. var p1p2 = vertex1.subtract(vertex2);
  47094. var p3p2 = vertex3.subtract(vertex2);
  47095. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  47096. }
  47097. if (useWorldCoordinates) {
  47098. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  47099. }
  47100. return BABYLON.Vector3.Normalize(result);
  47101. };
  47102. PickingInfo.prototype.getTextureCoordinates = function () {
  47103. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47104. return null;
  47105. }
  47106. var indices = this.pickedMesh.getIndices();
  47107. if (!indices) {
  47108. return null;
  47109. }
  47110. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47111. if (!uvs) {
  47112. return null;
  47113. }
  47114. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  47115. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  47116. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  47117. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  47118. uv1 = uv1.scale(this.bu);
  47119. uv2 = uv2.scale(this.bv);
  47120. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  47121. };
  47122. return PickingInfo;
  47123. }());
  47124. BABYLON.PickingInfo = PickingInfo;
  47125. })(BABYLON || (BABYLON = {}));
  47126. //# sourceMappingURL=babylon.pickingInfo.js.map
  47127. var BABYLON;
  47128. (function (BABYLON) {
  47129. var Ray = /** @class */ (function () {
  47130. function Ray(origin, direction, length) {
  47131. if (length === void 0) { length = Number.MAX_VALUE; }
  47132. this.origin = origin;
  47133. this.direction = direction;
  47134. this.length = length;
  47135. }
  47136. // Methods
  47137. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  47138. var d = 0.0;
  47139. var maxValue = Number.MAX_VALUE;
  47140. var inv;
  47141. var min;
  47142. var max;
  47143. var temp;
  47144. if (Math.abs(this.direction.x) < 0.0000001) {
  47145. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  47146. return false;
  47147. }
  47148. }
  47149. else {
  47150. inv = 1.0 / this.direction.x;
  47151. min = (minimum.x - this.origin.x) * inv;
  47152. max = (maximum.x - this.origin.x) * inv;
  47153. if (max === -Infinity) {
  47154. max = Infinity;
  47155. }
  47156. if (min > max) {
  47157. temp = min;
  47158. min = max;
  47159. max = temp;
  47160. }
  47161. d = Math.max(min, d);
  47162. maxValue = Math.min(max, maxValue);
  47163. if (d > maxValue) {
  47164. return false;
  47165. }
  47166. }
  47167. if (Math.abs(this.direction.y) < 0.0000001) {
  47168. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  47169. return false;
  47170. }
  47171. }
  47172. else {
  47173. inv = 1.0 / this.direction.y;
  47174. min = (minimum.y - this.origin.y) * inv;
  47175. max = (maximum.y - this.origin.y) * inv;
  47176. if (max === -Infinity) {
  47177. max = Infinity;
  47178. }
  47179. if (min > max) {
  47180. temp = min;
  47181. min = max;
  47182. max = temp;
  47183. }
  47184. d = Math.max(min, d);
  47185. maxValue = Math.min(max, maxValue);
  47186. if (d > maxValue) {
  47187. return false;
  47188. }
  47189. }
  47190. if (Math.abs(this.direction.z) < 0.0000001) {
  47191. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  47192. return false;
  47193. }
  47194. }
  47195. else {
  47196. inv = 1.0 / this.direction.z;
  47197. min = (minimum.z - this.origin.z) * inv;
  47198. max = (maximum.z - this.origin.z) * inv;
  47199. if (max === -Infinity) {
  47200. max = Infinity;
  47201. }
  47202. if (min > max) {
  47203. temp = min;
  47204. min = max;
  47205. max = temp;
  47206. }
  47207. d = Math.max(min, d);
  47208. maxValue = Math.min(max, maxValue);
  47209. if (d > maxValue) {
  47210. return false;
  47211. }
  47212. }
  47213. return true;
  47214. };
  47215. Ray.prototype.intersectsBox = function (box) {
  47216. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  47217. };
  47218. Ray.prototype.intersectsSphere = function (sphere) {
  47219. var x = sphere.center.x - this.origin.x;
  47220. var y = sphere.center.y - this.origin.y;
  47221. var z = sphere.center.z - this.origin.z;
  47222. var pyth = (x * x) + (y * y) + (z * z);
  47223. var rr = sphere.radius * sphere.radius;
  47224. if (pyth <= rr) {
  47225. return true;
  47226. }
  47227. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  47228. if (dot < 0.0) {
  47229. return false;
  47230. }
  47231. var temp = pyth - (dot * dot);
  47232. return temp <= rr;
  47233. };
  47234. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  47235. if (!this._edge1) {
  47236. this._edge1 = BABYLON.Vector3.Zero();
  47237. this._edge2 = BABYLON.Vector3.Zero();
  47238. this._pvec = BABYLON.Vector3.Zero();
  47239. this._tvec = BABYLON.Vector3.Zero();
  47240. this._qvec = BABYLON.Vector3.Zero();
  47241. }
  47242. vertex1.subtractToRef(vertex0, this._edge1);
  47243. vertex2.subtractToRef(vertex0, this._edge2);
  47244. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  47245. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  47246. if (det === 0) {
  47247. return null;
  47248. }
  47249. var invdet = 1 / det;
  47250. this.origin.subtractToRef(vertex0, this._tvec);
  47251. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  47252. if (bu < 0 || bu > 1.0) {
  47253. return null;
  47254. }
  47255. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  47256. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  47257. if (bv < 0 || bu + bv > 1.0) {
  47258. return null;
  47259. }
  47260. //check if the distance is longer than the predefined length.
  47261. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  47262. if (distance > this.length) {
  47263. return null;
  47264. }
  47265. return new BABYLON.IntersectionInfo(bu, bv, distance);
  47266. };
  47267. Ray.prototype.intersectsPlane = function (plane) {
  47268. var distance;
  47269. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  47270. if (Math.abs(result1) < 9.99999997475243E-07) {
  47271. return null;
  47272. }
  47273. else {
  47274. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  47275. distance = (-plane.d - result2) / result1;
  47276. if (distance < 0.0) {
  47277. if (distance < -9.99999997475243E-07) {
  47278. return null;
  47279. }
  47280. else {
  47281. return 0;
  47282. }
  47283. }
  47284. return distance;
  47285. }
  47286. };
  47287. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  47288. var tm = BABYLON.Tmp.Matrix[0];
  47289. mesh.getWorldMatrix().invertToRef(tm);
  47290. if (this._tmpRay) {
  47291. Ray.TransformToRef(this, tm, this._tmpRay);
  47292. }
  47293. else {
  47294. this._tmpRay = Ray.Transform(this, tm);
  47295. }
  47296. return mesh.intersects(this._tmpRay, fastCheck);
  47297. };
  47298. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  47299. if (results) {
  47300. results.length = 0;
  47301. }
  47302. else {
  47303. results = [];
  47304. }
  47305. for (var i = 0; i < meshes.length; i++) {
  47306. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  47307. if (pickInfo.hit) {
  47308. results.push(pickInfo);
  47309. }
  47310. }
  47311. results.sort(this._comparePickingInfo);
  47312. return results;
  47313. };
  47314. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  47315. if (pickingInfoA.distance < pickingInfoB.distance) {
  47316. return -1;
  47317. }
  47318. else if (pickingInfoA.distance > pickingInfoB.distance) {
  47319. return 1;
  47320. }
  47321. else {
  47322. return 0;
  47323. }
  47324. };
  47325. /**
  47326. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  47327. * @param sega the first point of the segment to test the intersection against
  47328. * @param segb the second point of the segment to test the intersection against
  47329. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  47330. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  47331. */
  47332. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  47333. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  47334. var u = segb.subtract(sega);
  47335. var v = rsegb.subtract(this.origin);
  47336. var w = sega.subtract(this.origin);
  47337. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  47338. var b = BABYLON.Vector3.Dot(u, v);
  47339. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  47340. var d = BABYLON.Vector3.Dot(u, w);
  47341. var e = BABYLON.Vector3.Dot(v, w);
  47342. var D = a * c - b * b; // always >= 0
  47343. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  47344. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  47345. // compute the line parameters of the two closest points
  47346. if (D < Ray.smallnum) {
  47347. sN = 0.0; // force using point P0 on segment S1
  47348. sD = 1.0; // to prevent possible division by 0.0 later
  47349. tN = e;
  47350. tD = c;
  47351. }
  47352. else {
  47353. sN = (b * e - c * d);
  47354. tN = (a * e - b * d);
  47355. if (sN < 0.0) {
  47356. sN = 0.0;
  47357. tN = e;
  47358. tD = c;
  47359. }
  47360. else if (sN > sD) {
  47361. sN = sD;
  47362. tN = e + b;
  47363. tD = c;
  47364. }
  47365. }
  47366. if (tN < 0.0) {
  47367. tN = 0.0;
  47368. // recompute sc for this edge
  47369. if (-d < 0.0) {
  47370. sN = 0.0;
  47371. }
  47372. else if (-d > a)
  47373. sN = sD;
  47374. else {
  47375. sN = -d;
  47376. sD = a;
  47377. }
  47378. }
  47379. else if (tN > tD) {
  47380. tN = tD;
  47381. // recompute sc for this edge
  47382. if ((-d + b) < 0.0) {
  47383. sN = 0;
  47384. }
  47385. else if ((-d + b) > a) {
  47386. sN = sD;
  47387. }
  47388. else {
  47389. sN = (-d + b);
  47390. sD = a;
  47391. }
  47392. }
  47393. // finally do the division to get sc and tc
  47394. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  47395. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  47396. // get the difference of the two closest points
  47397. var qtc = v.multiplyByFloats(tc, tc, tc);
  47398. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  47399. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  47400. if (isIntersected) {
  47401. return qtc.length();
  47402. }
  47403. return -1;
  47404. };
  47405. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47406. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  47407. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  47408. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  47409. this.direction.normalize();
  47410. return this;
  47411. };
  47412. // Statics
  47413. Ray.Zero = function () {
  47414. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  47415. };
  47416. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47417. var result = Ray.Zero();
  47418. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  47419. };
  47420. /**
  47421. * 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
  47422. * transformed to the given world matrix.
  47423. * @param origin The origin point
  47424. * @param end The end point
  47425. * @param world a matrix to transform the ray to. Default is the identity matrix.
  47426. */
  47427. Ray.CreateNewFromTo = function (origin, end, world) {
  47428. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  47429. var direction = end.subtract(origin);
  47430. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  47431. direction.normalize();
  47432. return Ray.Transform(new Ray(origin, direction, length), world);
  47433. };
  47434. Ray.Transform = function (ray, matrix) {
  47435. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  47436. Ray.TransformToRef(ray, matrix, result);
  47437. return result;
  47438. };
  47439. Ray.TransformToRef = function (ray, matrix, result) {
  47440. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  47441. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  47442. result.length = ray.length;
  47443. var dir = result.direction;
  47444. var len = dir.length();
  47445. if (!(len === 0 || len === 1)) {
  47446. var num = 1.0 / len;
  47447. dir.x *= num;
  47448. dir.y *= num;
  47449. dir.z *= num;
  47450. result.length *= len;
  47451. }
  47452. };
  47453. Ray.smallnum = 0.00000001;
  47454. Ray.rayl = 10e8;
  47455. return Ray;
  47456. }());
  47457. BABYLON.Ray = Ray;
  47458. })(BABYLON || (BABYLON = {}));
  47459. //# sourceMappingURL=babylon.ray.js.map
  47460. var BABYLON;
  47461. (function (BABYLON) {
  47462. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  47463. if (boxMin.x > sphereCenter.x + sphereRadius)
  47464. return false;
  47465. if (sphereCenter.x - sphereRadius > boxMax.x)
  47466. return false;
  47467. if (boxMin.y > sphereCenter.y + sphereRadius)
  47468. return false;
  47469. if (sphereCenter.y - sphereRadius > boxMax.y)
  47470. return false;
  47471. if (boxMin.z > sphereCenter.z + sphereRadius)
  47472. return false;
  47473. if (sphereCenter.z - sphereRadius > boxMax.z)
  47474. return false;
  47475. return true;
  47476. };
  47477. var getLowestRoot = (function () {
  47478. var result = { root: 0, found: false };
  47479. return function (a, b, c, maxR) {
  47480. result.root = 0;
  47481. result.found = false;
  47482. var determinant = b * b - 4.0 * a * c;
  47483. if (determinant < 0)
  47484. return result;
  47485. var sqrtD = Math.sqrt(determinant);
  47486. var r1 = (-b - sqrtD) / (2.0 * a);
  47487. var r2 = (-b + sqrtD) / (2.0 * a);
  47488. if (r1 > r2) {
  47489. var temp = r2;
  47490. r2 = r1;
  47491. r1 = temp;
  47492. }
  47493. if (r1 > 0 && r1 < maxR) {
  47494. result.root = r1;
  47495. result.found = true;
  47496. return result;
  47497. }
  47498. if (r2 > 0 && r2 < maxR) {
  47499. result.root = r2;
  47500. result.found = true;
  47501. return result;
  47502. }
  47503. return result;
  47504. };
  47505. })();
  47506. var Collider = /** @class */ (function () {
  47507. function Collider() {
  47508. this._collisionPoint = BABYLON.Vector3.Zero();
  47509. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47510. this._tempVector = BABYLON.Vector3.Zero();
  47511. this._tempVector2 = BABYLON.Vector3.Zero();
  47512. this._tempVector3 = BABYLON.Vector3.Zero();
  47513. this._tempVector4 = BABYLON.Vector3.Zero();
  47514. this._edge = BABYLON.Vector3.Zero();
  47515. this._baseToVertex = BABYLON.Vector3.Zero();
  47516. this._destinationPoint = BABYLON.Vector3.Zero();
  47517. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47518. this._displacementVector = BABYLON.Vector3.Zero();
  47519. this._radius = BABYLON.Vector3.One();
  47520. this._retry = 0;
  47521. this._basePointWorld = BABYLON.Vector3.Zero();
  47522. this._velocityWorld = BABYLON.Vector3.Zero();
  47523. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47524. this._collisionMask = -1;
  47525. }
  47526. Object.defineProperty(Collider.prototype, "collisionMask", {
  47527. get: function () {
  47528. return this._collisionMask;
  47529. },
  47530. set: function (mask) {
  47531. this._collisionMask = !isNaN(mask) ? mask : -1;
  47532. },
  47533. enumerable: true,
  47534. configurable: true
  47535. });
  47536. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47537. /**
  47538. * Gets the plane normal used to compute the sliding response (in local space)
  47539. */
  47540. get: function () {
  47541. return this._slidePlaneNormal;
  47542. },
  47543. enumerable: true,
  47544. configurable: true
  47545. });
  47546. // Methods
  47547. Collider.prototype._initialize = function (source, dir, e) {
  47548. this._velocity = dir;
  47549. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47550. this._basePoint = source;
  47551. source.multiplyToRef(this._radius, this._basePointWorld);
  47552. dir.multiplyToRef(this._radius, this._velocityWorld);
  47553. this._velocityWorldLength = this._velocityWorld.length();
  47554. this._epsilon = e;
  47555. this.collisionFound = false;
  47556. };
  47557. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47558. pa.subtractToRef(point, this._tempVector);
  47559. pb.subtractToRef(point, this._tempVector2);
  47560. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47561. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47562. if (d < 0)
  47563. return false;
  47564. pc.subtractToRef(point, this._tempVector3);
  47565. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47566. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47567. if (d < 0)
  47568. return false;
  47569. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47570. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47571. return d >= 0;
  47572. };
  47573. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47574. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47575. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47576. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47577. return false;
  47578. }
  47579. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47580. return false;
  47581. return true;
  47582. };
  47583. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47584. var t0;
  47585. var embeddedInPlane = false;
  47586. //defensive programming, actually not needed.
  47587. if (!trianglePlaneArray) {
  47588. trianglePlaneArray = [];
  47589. }
  47590. if (!trianglePlaneArray[faceIndex]) {
  47591. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47592. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47593. }
  47594. var trianglePlane = trianglePlaneArray[faceIndex];
  47595. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47596. return;
  47597. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47598. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47599. if (normalDotVelocity == 0) {
  47600. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47601. return;
  47602. embeddedInPlane = true;
  47603. t0 = 0;
  47604. }
  47605. else {
  47606. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47607. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47608. if (t0 > t1) {
  47609. var temp = t1;
  47610. t1 = t0;
  47611. t0 = temp;
  47612. }
  47613. if (t0 > 1.0 || t1 < 0.0)
  47614. return;
  47615. if (t0 < 0)
  47616. t0 = 0;
  47617. if (t0 > 1.0)
  47618. t0 = 1.0;
  47619. }
  47620. this._collisionPoint.copyFromFloats(0, 0, 0);
  47621. var found = false;
  47622. var t = 1.0;
  47623. if (!embeddedInPlane) {
  47624. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47625. this._velocity.scaleToRef(t0, this._tempVector);
  47626. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47627. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47628. found = true;
  47629. t = t0;
  47630. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47631. }
  47632. }
  47633. if (!found) {
  47634. var velocitySquaredLength = this._velocity.lengthSquared();
  47635. var a = velocitySquaredLength;
  47636. this._basePoint.subtractToRef(p1, this._tempVector);
  47637. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47638. var c = this._tempVector.lengthSquared() - 1.0;
  47639. var lowestRoot = getLowestRoot(a, b, c, t);
  47640. if (lowestRoot.found) {
  47641. t = lowestRoot.root;
  47642. found = true;
  47643. this._collisionPoint.copyFrom(p1);
  47644. }
  47645. this._basePoint.subtractToRef(p2, this._tempVector);
  47646. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47647. c = this._tempVector.lengthSquared() - 1.0;
  47648. lowestRoot = getLowestRoot(a, b, c, t);
  47649. if (lowestRoot.found) {
  47650. t = lowestRoot.root;
  47651. found = true;
  47652. this._collisionPoint.copyFrom(p2);
  47653. }
  47654. this._basePoint.subtractToRef(p3, this._tempVector);
  47655. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47656. c = this._tempVector.lengthSquared() - 1.0;
  47657. lowestRoot = getLowestRoot(a, b, c, t);
  47658. if (lowestRoot.found) {
  47659. t = lowestRoot.root;
  47660. found = true;
  47661. this._collisionPoint.copyFrom(p3);
  47662. }
  47663. p2.subtractToRef(p1, this._edge);
  47664. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47665. var edgeSquaredLength = this._edge.lengthSquared();
  47666. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47667. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47668. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47669. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47670. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47671. lowestRoot = getLowestRoot(a, b, c, t);
  47672. if (lowestRoot.found) {
  47673. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47674. if (f >= 0.0 && f <= 1.0) {
  47675. t = lowestRoot.root;
  47676. found = true;
  47677. this._edge.scaleInPlace(f);
  47678. p1.addToRef(this._edge, this._collisionPoint);
  47679. }
  47680. }
  47681. p3.subtractToRef(p2, this._edge);
  47682. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47683. edgeSquaredLength = this._edge.lengthSquared();
  47684. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47685. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47686. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47687. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47688. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47689. lowestRoot = getLowestRoot(a, b, c, t);
  47690. if (lowestRoot.found) {
  47691. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47692. if (f >= 0.0 && f <= 1.0) {
  47693. t = lowestRoot.root;
  47694. found = true;
  47695. this._edge.scaleInPlace(f);
  47696. p2.addToRef(this._edge, this._collisionPoint);
  47697. }
  47698. }
  47699. p1.subtractToRef(p3, this._edge);
  47700. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47701. edgeSquaredLength = this._edge.lengthSquared();
  47702. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47703. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47704. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47705. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47706. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47707. lowestRoot = getLowestRoot(a, b, c, t);
  47708. if (lowestRoot.found) {
  47709. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47710. if (f >= 0.0 && f <= 1.0) {
  47711. t = lowestRoot.root;
  47712. found = true;
  47713. this._edge.scaleInPlace(f);
  47714. p3.addToRef(this._edge, this._collisionPoint);
  47715. }
  47716. }
  47717. }
  47718. if (found) {
  47719. var distToCollision = t * this._velocity.length();
  47720. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47721. if (!this.intersectionPoint) {
  47722. this.intersectionPoint = this._collisionPoint.clone();
  47723. }
  47724. else {
  47725. this.intersectionPoint.copyFrom(this._collisionPoint);
  47726. }
  47727. this._nearestDistance = distToCollision;
  47728. this.collisionFound = true;
  47729. }
  47730. }
  47731. };
  47732. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47733. for (var i = indexStart; i < indexEnd; i += 3) {
  47734. var p1 = pts[indices[i] - decal];
  47735. var p2 = pts[indices[i + 1] - decal];
  47736. var p3 = pts[indices[i + 2] - decal];
  47737. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47738. }
  47739. };
  47740. Collider.prototype._getResponse = function (pos, vel) {
  47741. pos.addToRef(vel, this._destinationPoint);
  47742. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47743. this._basePoint.addToRef(vel, pos);
  47744. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47745. this._slidePlaneNormal.normalize();
  47746. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47747. pos.addInPlace(this._displacementVector);
  47748. this.intersectionPoint.addInPlace(this._displacementVector);
  47749. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47750. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47751. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47752. };
  47753. return Collider;
  47754. }());
  47755. BABYLON.Collider = Collider;
  47756. })(BABYLON || (BABYLON = {}));
  47757. //# sourceMappingURL=babylon.collider.js.map
  47758. var BABYLON;
  47759. (function (BABYLON) {
  47760. //WebWorker code will be inserted to this variable.
  47761. BABYLON.CollisionWorker = "";
  47762. var WorkerTaskType;
  47763. (function (WorkerTaskType) {
  47764. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47765. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47766. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47767. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47768. var WorkerReplyType;
  47769. (function (WorkerReplyType) {
  47770. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  47771. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  47772. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  47773. var CollisionCoordinatorWorker = /** @class */ (function () {
  47774. function CollisionCoordinatorWorker() {
  47775. var _this = this;
  47776. this._scaledPosition = BABYLON.Vector3.Zero();
  47777. this._scaledVelocity = BABYLON.Vector3.Zero();
  47778. this.onMeshUpdated = function (transformNode) {
  47779. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  47780. };
  47781. this.onGeometryUpdated = function (geometry) {
  47782. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  47783. };
  47784. this._afterRender = function () {
  47785. if (!_this._init)
  47786. return;
  47787. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  47788. return;
  47789. }
  47790. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  47791. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  47792. if (_this._runningUpdated > 4) {
  47793. return;
  47794. }
  47795. ++_this._runningUpdated;
  47796. var payload = {
  47797. updatedMeshes: _this._addUpdateMeshesList,
  47798. updatedGeometries: _this._addUpdateGeometriesList,
  47799. removedGeometries: _this._toRemoveGeometryArray,
  47800. removedMeshes: _this._toRemoveMeshesArray
  47801. };
  47802. var message = {
  47803. payload: payload,
  47804. taskType: WorkerTaskType.UPDATE
  47805. };
  47806. var serializable = [];
  47807. for (var id in payload.updatedGeometries) {
  47808. if (payload.updatedGeometries.hasOwnProperty(id)) {
  47809. //prepare transferables
  47810. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  47811. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  47812. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  47813. }
  47814. }
  47815. _this._worker.postMessage(message, serializable);
  47816. _this._addUpdateMeshesList = {};
  47817. _this._addUpdateGeometriesList = {};
  47818. _this._toRemoveGeometryArray = [];
  47819. _this._toRemoveMeshesArray = [];
  47820. };
  47821. this._onMessageFromWorker = function (e) {
  47822. var returnData = e.data;
  47823. if (returnData.error != WorkerReplyType.SUCCESS) {
  47824. //TODO what errors can be returned from the worker?
  47825. BABYLON.Tools.Warn("error returned from worker!");
  47826. return;
  47827. }
  47828. switch (returnData.taskType) {
  47829. case WorkerTaskType.INIT:
  47830. _this._init = true;
  47831. //Update the worked with ALL of the scene's current state
  47832. _this._scene.meshes.forEach(function (mesh) {
  47833. _this.onMeshAdded(mesh);
  47834. });
  47835. _this._scene.getGeometries().forEach(function (geometry) {
  47836. _this.onGeometryAdded(geometry);
  47837. });
  47838. break;
  47839. case WorkerTaskType.UPDATE:
  47840. _this._runningUpdated--;
  47841. break;
  47842. case WorkerTaskType.COLLIDE:
  47843. var returnPayload = returnData.payload;
  47844. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47845. return;
  47846. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47847. if (callback) {
  47848. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47849. if (mesh) {
  47850. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47851. }
  47852. }
  47853. //cleanup
  47854. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47855. break;
  47856. }
  47857. };
  47858. this._collisionsCallbackArray = [];
  47859. this._init = false;
  47860. this._runningUpdated = 0;
  47861. this._addUpdateMeshesList = {};
  47862. this._addUpdateGeometriesList = {};
  47863. this._toRemoveGeometryArray = [];
  47864. this._toRemoveMeshesArray = [];
  47865. }
  47866. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47867. if (!this._init)
  47868. return;
  47869. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47870. return;
  47871. position.divideToRef(collider._radius, this._scaledPosition);
  47872. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47873. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47874. var payload = {
  47875. collider: {
  47876. position: this._scaledPosition.asArray(),
  47877. velocity: this._scaledVelocity.asArray(),
  47878. radius: collider._radius.asArray()
  47879. },
  47880. collisionId: collisionIndex,
  47881. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47882. maximumRetry: maximumRetry
  47883. };
  47884. var message = {
  47885. payload: payload,
  47886. taskType: WorkerTaskType.COLLIDE
  47887. };
  47888. this._worker.postMessage(message);
  47889. };
  47890. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47891. this._scene = scene;
  47892. this._scene.registerAfterRender(this._afterRender);
  47893. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47894. this._worker = new Worker(workerUrl);
  47895. this._worker.onmessage = this._onMessageFromWorker;
  47896. var message = {
  47897. payload: {},
  47898. taskType: WorkerTaskType.INIT
  47899. };
  47900. this._worker.postMessage(message);
  47901. };
  47902. CollisionCoordinatorWorker.prototype.destroy = function () {
  47903. this._scene.unregisterAfterRender(this._afterRender);
  47904. this._worker.terminate();
  47905. };
  47906. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47907. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47908. this.onMeshUpdated(mesh);
  47909. };
  47910. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47911. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47912. };
  47913. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47914. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47915. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47916. this.onGeometryUpdated(geometry);
  47917. };
  47918. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47919. this._toRemoveGeometryArray.push(geometry.id);
  47920. };
  47921. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47922. var submeshes = [];
  47923. if (mesh.subMeshes) {
  47924. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47925. var boundingInfo = sm.getBoundingInfo();
  47926. return {
  47927. position: idx,
  47928. verticesStart: sm.verticesStart,
  47929. verticesCount: sm.verticesCount,
  47930. indexStart: sm.indexStart,
  47931. indexCount: sm.indexCount,
  47932. hasMaterial: !!sm.getMaterial(),
  47933. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47934. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47935. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47936. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47937. };
  47938. });
  47939. }
  47940. var geometryId = null;
  47941. if (mesh instanceof BABYLON.Mesh) {
  47942. var geometry = mesh.geometry;
  47943. geometryId = geometry ? geometry.id : null;
  47944. }
  47945. else if (mesh instanceof BABYLON.InstancedMesh) {
  47946. var geometry = mesh.sourceMesh.geometry;
  47947. geometryId = geometry ? geometry.id : null;
  47948. }
  47949. var boundingInfo = mesh.getBoundingInfo();
  47950. return {
  47951. uniqueId: mesh.uniqueId,
  47952. id: mesh.id,
  47953. name: mesh.name,
  47954. geometryId: geometryId,
  47955. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47956. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47957. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47958. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47959. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47960. subMeshes: submeshes,
  47961. checkCollisions: mesh.checkCollisions
  47962. };
  47963. };
  47964. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47965. return {
  47966. id: geometry.id,
  47967. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47968. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47969. indices: new Uint32Array(geometry.getIndices() || []),
  47970. };
  47971. };
  47972. return CollisionCoordinatorWorker;
  47973. }());
  47974. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47975. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47976. function CollisionCoordinatorLegacy() {
  47977. this._scaledPosition = BABYLON.Vector3.Zero();
  47978. this._scaledVelocity = BABYLON.Vector3.Zero();
  47979. this._finalPosition = BABYLON.Vector3.Zero();
  47980. }
  47981. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47982. position.divideToRef(collider._radius, this._scaledPosition);
  47983. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47984. collider.collidedMesh = null;
  47985. collider._retry = 0;
  47986. collider._initialVelocity = this._scaledVelocity;
  47987. collider._initialPosition = this._scaledPosition;
  47988. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47989. this._finalPosition.multiplyInPlace(collider._radius);
  47990. //run the callback
  47991. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47992. };
  47993. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47994. this._scene = scene;
  47995. };
  47996. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47997. //Legacy need no destruction method.
  47998. };
  47999. //No update in legacy mode
  48000. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  48001. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  48002. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  48003. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  48004. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  48005. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  48006. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  48007. if (excludedMesh === void 0) { excludedMesh = null; }
  48008. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  48009. if (collider._retry >= maximumRetry) {
  48010. finalPosition.copyFrom(position);
  48011. return;
  48012. }
  48013. // Check if this is a mesh else camera or -1
  48014. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  48015. collider._initialize(position, velocity, closeDistance);
  48016. // Check all meshes
  48017. for (var index = 0; index < this._scene.meshes.length; index++) {
  48018. var mesh = this._scene.meshes[index];
  48019. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  48020. mesh._checkCollision(collider);
  48021. }
  48022. }
  48023. if (!collider.collisionFound) {
  48024. position.addToRef(velocity, finalPosition);
  48025. return;
  48026. }
  48027. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  48028. collider._getResponse(position, velocity);
  48029. }
  48030. if (velocity.length() <= closeDistance) {
  48031. finalPosition.copyFrom(position);
  48032. return;
  48033. }
  48034. collider._retry++;
  48035. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  48036. };
  48037. return CollisionCoordinatorLegacy;
  48038. }());
  48039. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  48040. })(BABYLON || (BABYLON = {}));
  48041. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  48042. var BABYLON;
  48043. (function (BABYLON) {
  48044. /**
  48045. * A particle represents one of the element emitted by a particle system.
  48046. * This is mainly define by its coordinates, direction, velocity and age.
  48047. */
  48048. var Particle = /** @class */ (function () {
  48049. /**
  48050. * Creates a new instance of @see Particle
  48051. * @param particleSystem the particle system the particle belongs to
  48052. */
  48053. function Particle(particleSystem) {
  48054. this.particleSystem = particleSystem;
  48055. /**
  48056. * The world position of the particle in the scene.
  48057. */
  48058. this.position = BABYLON.Vector3.Zero();
  48059. /**
  48060. * The world direction of the particle in the scene.
  48061. */
  48062. this.direction = BABYLON.Vector3.Zero();
  48063. /**
  48064. * The color of the particle.
  48065. */
  48066. this.color = new BABYLON.Color4(0, 0, 0, 0);
  48067. /**
  48068. * The color change of the particle per step.
  48069. */
  48070. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  48071. /**
  48072. * Defines how long will the life of the particle be.
  48073. */
  48074. this.lifeTime = 1.0;
  48075. /**
  48076. * The current age of the particle.
  48077. */
  48078. this.age = 0;
  48079. /**
  48080. * The current size of the particle.
  48081. */
  48082. this.size = 0;
  48083. /**
  48084. * The current angle of the particle.
  48085. */
  48086. this.angle = 0;
  48087. /**
  48088. * Defines how fast is the angle changing.
  48089. */
  48090. this.angularSpeed = 0;
  48091. /**
  48092. * Defines the cell index used by the particle to be rendered from a sprite.
  48093. */
  48094. this.cellIndex = 0;
  48095. this._currentFrameCounter = 0;
  48096. if (!this.particleSystem.isAnimationSheetEnabled) {
  48097. return;
  48098. }
  48099. this.cellIndex = this.particleSystem.startSpriteCellID;
  48100. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  48101. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  48102. }
  48103. else {
  48104. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  48105. }
  48106. }
  48107. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  48108. // (ageOffset / scaledUpdateSpeed) / available cells
  48109. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  48110. this._currentFrameCounter += scaledUpdateSpeed;
  48111. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  48112. this._currentFrameCounter = 0;
  48113. this.cellIndex++;
  48114. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48115. this.cellIndex = this.particleSystem.endSpriteCellID;
  48116. }
  48117. }
  48118. };
  48119. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  48120. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  48121. this.cellIndex++;
  48122. this._currentFrameCounter = 0;
  48123. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48124. if (this.particleSystem.spriteCellLoop) {
  48125. this.cellIndex = this.particleSystem.startSpriteCellID;
  48126. }
  48127. else {
  48128. this.cellIndex = this.particleSystem.endSpriteCellID;
  48129. }
  48130. }
  48131. }
  48132. else {
  48133. this._currentFrameCounter++;
  48134. }
  48135. };
  48136. /**
  48137. * Copy the properties of particle to another one.
  48138. * @param other the particle to copy the information to.
  48139. */
  48140. Particle.prototype.copyTo = function (other) {
  48141. other.position.copyFrom(this.position);
  48142. other.direction.copyFrom(this.direction);
  48143. other.color.copyFrom(this.color);
  48144. other.colorStep.copyFrom(this.colorStep);
  48145. other.lifeTime = this.lifeTime;
  48146. other.age = this.age;
  48147. other.size = this.size;
  48148. other.angle = this.angle;
  48149. other.angularSpeed = this.angularSpeed;
  48150. other.particleSystem = this.particleSystem;
  48151. other.cellIndex = this.cellIndex;
  48152. };
  48153. return Particle;
  48154. }());
  48155. BABYLON.Particle = Particle;
  48156. })(BABYLON || (BABYLON = {}));
  48157. //# sourceMappingURL=babylon.particle.js.map
  48158. var BABYLON;
  48159. (function (BABYLON) {
  48160. /**
  48161. * This represents a particle system in Babylon.
  48162. * 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.
  48163. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  48164. * @example https://doc.babylonjs.com/babylon101/particles
  48165. */
  48166. var ParticleSystem = /** @class */ (function () {
  48167. /**
  48168. * Instantiates a particle system.
  48169. * 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.
  48170. * @param name The name of the particle system
  48171. * @param capacity The max number of particles alive at the same time
  48172. * @param scene The scene the particle system belongs to
  48173. * @param customEffect a custom effect used to change the way particles are rendered by default
  48174. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  48175. * @param epsilon Offset used to render the particles
  48176. */
  48177. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  48178. if (customEffect === void 0) { customEffect = null; }
  48179. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  48180. if (epsilon === void 0) { epsilon = 0.01; }
  48181. var _this = this;
  48182. /**
  48183. * List of animations used by the particle system.
  48184. */
  48185. this.animations = [];
  48186. /**
  48187. * The rendering group used by the Particle system to chose when to render.
  48188. */
  48189. this.renderingGroupId = 0;
  48190. /**
  48191. * The emitter represents the Mesh or position we are attaching the particle system to.
  48192. */
  48193. this.emitter = null;
  48194. /**
  48195. * The density of particles, the rate of particle flow
  48196. */
  48197. this.emitRate = 10;
  48198. /**
  48199. * If you want to launch only a few particles at once, that can be done, as well.
  48200. */
  48201. this.manualEmitCount = -1;
  48202. /**
  48203. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  48204. */
  48205. this.updateSpeed = 0.01;
  48206. /**
  48207. * The amount of time the particle system is running (depends of the overall speed above).
  48208. */
  48209. this.targetStopDuration = 0;
  48210. /**
  48211. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  48212. */
  48213. this.disposeOnStop = false;
  48214. /**
  48215. * Minimum power of emitting particles.
  48216. */
  48217. this.minEmitPower = 1;
  48218. /**
  48219. * Maximum power of emitting particles.
  48220. */
  48221. this.maxEmitPower = 1;
  48222. /**
  48223. * Minimum life time of emitting particles.
  48224. */
  48225. this.minLifeTime = 1;
  48226. /**
  48227. * Maximum life time of emitting particles.
  48228. */
  48229. this.maxLifeTime = 1;
  48230. /**
  48231. * Minimum Size of emitting particles.
  48232. */
  48233. this.minSize = 1;
  48234. /**
  48235. * Maximum Size of emitting particles.
  48236. */
  48237. this.maxSize = 1;
  48238. /**
  48239. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  48240. */
  48241. this.minAngularSpeed = 0;
  48242. /**
  48243. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  48244. */
  48245. this.maxAngularSpeed = 0;
  48246. /**
  48247. * The layer mask we are rendering the particles through.
  48248. */
  48249. this.layerMask = 0x0FFFFFFF;
  48250. /**
  48251. * This can help using your own shader to render the particle system.
  48252. * The according effect will be created
  48253. */
  48254. this.customShader = null;
  48255. /**
  48256. * By default particle system starts as soon as they are created. This prevents the
  48257. * automatic start to happen and let you decide when to start emitting particles.
  48258. */
  48259. this.preventAutoStart = false;
  48260. /**
  48261. * Callback triggered when the particle animation is ending.
  48262. */
  48263. this.onAnimationEnd = null;
  48264. /**
  48265. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  48266. */
  48267. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  48268. /**
  48269. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  48270. * to override the particles.
  48271. */
  48272. this.forceDepthWrite = false;
  48273. /**
  48274. * You can use gravity if you want to give an orientation to your particles.
  48275. */
  48276. this.gravity = BABYLON.Vector3.Zero();
  48277. /**
  48278. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48279. */
  48280. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  48281. /**
  48282. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48283. */
  48284. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  48285. /**
  48286. * 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.
  48287. */
  48288. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  48289. /**
  48290. * 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.
  48291. */
  48292. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48293. /**
  48294. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48295. */
  48296. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48297. /**
  48298. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48299. */
  48300. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48301. /**
  48302. * Color the particle will have at the end of its lifetime.
  48303. */
  48304. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  48305. /**
  48306. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  48307. */
  48308. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48309. /**
  48310. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  48311. */
  48312. this.spriteCellLoop = true;
  48313. /**
  48314. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  48315. */
  48316. this.spriteCellChangeSpeed = 0;
  48317. /**
  48318. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  48319. */
  48320. this.startSpriteCellID = 0;
  48321. /**
  48322. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  48323. */
  48324. this.endSpriteCellID = 0;
  48325. /**
  48326. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  48327. */
  48328. this.spriteCellWidth = 0;
  48329. /**
  48330. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  48331. */
  48332. this.spriteCellHeight = 0;
  48333. /**
  48334. * An event triggered when the system is disposed.
  48335. */
  48336. this.onDisposeObservable = new BABYLON.Observable();
  48337. this._particles = new Array();
  48338. this._stockParticles = new Array();
  48339. this._newPartsExcess = 0;
  48340. this._vertexBuffers = {};
  48341. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  48342. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48343. this._scaledDirection = BABYLON.Vector3.Zero();
  48344. this._scaledGravity = BABYLON.Vector3.Zero();
  48345. this._currentRenderId = -1;
  48346. this._started = false;
  48347. this._stopped = false;
  48348. this._actualFrame = 0;
  48349. this._vertexBufferSize = 11;
  48350. this._appendParticleVertexes = null;
  48351. this.id = name;
  48352. this.name = name;
  48353. this._capacity = capacity;
  48354. this._epsilon = epsilon;
  48355. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  48356. if (isAnimationSheetEnabled) {
  48357. this._vertexBufferSize = 12;
  48358. }
  48359. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48360. this._customEffect = customEffect;
  48361. scene.particleSystems.push(this);
  48362. this._createIndexBuffer();
  48363. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  48364. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  48365. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  48366. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  48367. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  48368. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  48369. if (this._isAnimationSheetEnabled) {
  48370. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  48371. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  48372. }
  48373. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48374. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48375. this._vertexBuffers["options"] = options;
  48376. // Default behaviors
  48377. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  48378. this.updateFunction = function (particles) {
  48379. for (var index = 0; index < particles.length; index++) {
  48380. var particle = particles[index];
  48381. particle.age += _this._scaledUpdateSpeed;
  48382. if (particle.age >= particle.lifeTime) {
  48383. _this.recycleParticle(particle);
  48384. index--;
  48385. continue;
  48386. }
  48387. else {
  48388. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  48389. particle.color.addInPlace(_this._scaledColorStep);
  48390. if (particle.color.a < 0)
  48391. particle.color.a = 0;
  48392. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  48393. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  48394. particle.position.addInPlace(_this._scaledDirection);
  48395. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  48396. particle.direction.addInPlace(_this._scaledGravity);
  48397. if (_this._isAnimationSheetEnabled) {
  48398. particle.updateCellIndex(_this._scaledUpdateSpeed);
  48399. }
  48400. }
  48401. }
  48402. };
  48403. }
  48404. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  48405. /**
  48406. * Sets a callback that will be triggered when the system is disposed.
  48407. */
  48408. set: function (callback) {
  48409. if (this._onDisposeObserver) {
  48410. this.onDisposeObservable.remove(this._onDisposeObserver);
  48411. }
  48412. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48413. },
  48414. enumerable: true,
  48415. configurable: true
  48416. });
  48417. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  48418. /**
  48419. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  48420. */
  48421. get: function () {
  48422. return this._isAnimationSheetEnabled;
  48423. },
  48424. enumerable: true,
  48425. configurable: true
  48426. });
  48427. ParticleSystem.prototype._createIndexBuffer = function () {
  48428. var indices = [];
  48429. var index = 0;
  48430. for (var count = 0; count < this._capacity; count++) {
  48431. indices.push(index);
  48432. indices.push(index + 1);
  48433. indices.push(index + 2);
  48434. indices.push(index);
  48435. indices.push(index + 2);
  48436. indices.push(index + 3);
  48437. index += 4;
  48438. }
  48439. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  48440. };
  48441. /**
  48442. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  48443. * Its lifetime will start back at 0.
  48444. * @param particle The particle to recycle
  48445. */
  48446. ParticleSystem.prototype.recycleParticle = function (particle) {
  48447. var lastParticle = this._particles.pop();
  48448. if (lastParticle !== particle) {
  48449. lastParticle.copyTo(particle);
  48450. this._stockParticles.push(lastParticle);
  48451. }
  48452. };
  48453. /**
  48454. * Gets the maximum number of particles active at the same time.
  48455. * @returns The max number of active particles.
  48456. */
  48457. ParticleSystem.prototype.getCapacity = function () {
  48458. return this._capacity;
  48459. };
  48460. /**
  48461. * Gets Wether there are still active particles in the system.
  48462. * @returns True if it is alive, otherwise false.
  48463. */
  48464. ParticleSystem.prototype.isAlive = function () {
  48465. return this._alive;
  48466. };
  48467. /**
  48468. * Gets Wether the system has been started.
  48469. * @returns True if it has been started, otherwise false.
  48470. */
  48471. ParticleSystem.prototype.isStarted = function () {
  48472. return this._started;
  48473. };
  48474. /**
  48475. * Starts the particle system and begins to emit.
  48476. */
  48477. ParticleSystem.prototype.start = function () {
  48478. this._started = true;
  48479. this._stopped = false;
  48480. this._actualFrame = 0;
  48481. };
  48482. /**
  48483. * Stops the particle system.
  48484. */
  48485. ParticleSystem.prototype.stop = function () {
  48486. this._stopped = true;
  48487. };
  48488. /**
  48489. * @ignore (for internal use only)
  48490. */
  48491. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  48492. var offset = index * this._vertexBufferSize;
  48493. this._vertexData[offset] = particle.position.x;
  48494. this._vertexData[offset + 1] = particle.position.y;
  48495. this._vertexData[offset + 2] = particle.position.z;
  48496. this._vertexData[offset + 3] = particle.color.r;
  48497. this._vertexData[offset + 4] = particle.color.g;
  48498. this._vertexData[offset + 5] = particle.color.b;
  48499. this._vertexData[offset + 6] = particle.color.a;
  48500. this._vertexData[offset + 7] = particle.angle;
  48501. this._vertexData[offset + 8] = particle.size;
  48502. this._vertexData[offset + 9] = offsetX;
  48503. this._vertexData[offset + 10] = offsetY;
  48504. };
  48505. /**
  48506. * @ignore (for internal use only)
  48507. */
  48508. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48509. if (offsetX === 0)
  48510. offsetX = this._epsilon;
  48511. else if (offsetX === 1)
  48512. offsetX = 1 - this._epsilon;
  48513. if (offsetY === 0)
  48514. offsetY = this._epsilon;
  48515. else if (offsetY === 1)
  48516. offsetY = 1 - this._epsilon;
  48517. var offset = index * this._vertexBufferSize;
  48518. this._vertexData[offset] = particle.position.x;
  48519. this._vertexData[offset + 1] = particle.position.y;
  48520. this._vertexData[offset + 2] = particle.position.z;
  48521. this._vertexData[offset + 3] = particle.color.r;
  48522. this._vertexData[offset + 4] = particle.color.g;
  48523. this._vertexData[offset + 5] = particle.color.b;
  48524. this._vertexData[offset + 6] = particle.color.a;
  48525. this._vertexData[offset + 7] = particle.angle;
  48526. this._vertexData[offset + 8] = particle.size;
  48527. this._vertexData[offset + 9] = offsetX;
  48528. this._vertexData[offset + 10] = offsetY;
  48529. this._vertexData[offset + 11] = particle.cellIndex;
  48530. };
  48531. ParticleSystem.prototype._update = function (newParticles) {
  48532. // Update current
  48533. this._alive = this._particles.length > 0;
  48534. this.updateFunction(this._particles);
  48535. // Add new ones
  48536. var worldMatrix;
  48537. if (this.emitter.position) {
  48538. var emitterMesh = this.emitter;
  48539. worldMatrix = emitterMesh.getWorldMatrix();
  48540. }
  48541. else {
  48542. var emitterPosition = this.emitter;
  48543. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48544. }
  48545. var particle;
  48546. for (var index = 0; index < newParticles; index++) {
  48547. if (this._particles.length === this._capacity) {
  48548. break;
  48549. }
  48550. if (this._stockParticles.length !== 0) {
  48551. particle = this._stockParticles.pop();
  48552. particle.age = 0;
  48553. particle.cellIndex = this.startSpriteCellID;
  48554. }
  48555. else {
  48556. particle = new BABYLON.Particle(this);
  48557. }
  48558. this._particles.push(particle);
  48559. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48560. if (this.startPositionFunction) {
  48561. this.startPositionFunction(worldMatrix, particle.position, particle);
  48562. }
  48563. else {
  48564. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48565. }
  48566. if (this.startDirectionFunction) {
  48567. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48568. }
  48569. else {
  48570. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48571. }
  48572. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48573. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48574. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48575. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48576. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48577. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48578. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48579. }
  48580. };
  48581. ParticleSystem.prototype._getEffect = function () {
  48582. if (this._customEffect) {
  48583. return this._customEffect;
  48584. }
  48585. ;
  48586. var defines = [];
  48587. if (this._scene.clipPlane) {
  48588. defines.push("#define CLIPPLANE");
  48589. }
  48590. if (this._isAnimationSheetEnabled) {
  48591. defines.push("#define ANIMATESHEET");
  48592. }
  48593. // Effect
  48594. var join = defines.join("\n");
  48595. if (this._cachedDefines !== join) {
  48596. this._cachedDefines = join;
  48597. var attributesNamesOrOptions;
  48598. var effectCreationOption;
  48599. if (this._isAnimationSheetEnabled) {
  48600. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48601. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48602. }
  48603. else {
  48604. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48605. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48606. }
  48607. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48608. }
  48609. return this._effect;
  48610. };
  48611. /**
  48612. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48613. */
  48614. ParticleSystem.prototype.animate = function () {
  48615. if (!this._started)
  48616. return;
  48617. var effect = this._getEffect();
  48618. // Check
  48619. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48620. return;
  48621. if (this._currentRenderId === this._scene.getRenderId()) {
  48622. return;
  48623. }
  48624. this._currentRenderId = this._scene.getRenderId();
  48625. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48626. // determine the number of particles we need to create
  48627. var newParticles;
  48628. if (this.manualEmitCount > -1) {
  48629. newParticles = this.manualEmitCount;
  48630. this._newPartsExcess = 0;
  48631. this.manualEmitCount = 0;
  48632. }
  48633. else {
  48634. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48635. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48636. }
  48637. if (this._newPartsExcess > 1.0) {
  48638. newParticles += this._newPartsExcess >> 0;
  48639. this._newPartsExcess -= this._newPartsExcess >> 0;
  48640. }
  48641. this._alive = false;
  48642. if (!this._stopped) {
  48643. this._actualFrame += this._scaledUpdateSpeed;
  48644. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48645. this.stop();
  48646. }
  48647. else {
  48648. newParticles = 0;
  48649. }
  48650. this._update(newParticles);
  48651. // Stopped?
  48652. if (this._stopped) {
  48653. if (!this._alive) {
  48654. this._started = false;
  48655. if (this.onAnimationEnd) {
  48656. this.onAnimationEnd();
  48657. }
  48658. if (this.disposeOnStop) {
  48659. this._scene._toBeDisposed.push(this);
  48660. }
  48661. }
  48662. }
  48663. // Animation sheet
  48664. if (this._isAnimationSheetEnabled) {
  48665. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48666. }
  48667. else {
  48668. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48669. }
  48670. // Update VBO
  48671. var offset = 0;
  48672. for (var index = 0; index < this._particles.length; index++) {
  48673. var particle = this._particles[index];
  48674. this._appendParticleVertexes(offset, particle);
  48675. offset += 4;
  48676. }
  48677. if (this._vertexBuffer) {
  48678. this._vertexBuffer.update(this._vertexData);
  48679. }
  48680. };
  48681. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48682. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48683. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48684. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48685. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48686. };
  48687. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48688. this._appendParticleVertex(offset++, particle, 0, 0);
  48689. this._appendParticleVertex(offset++, particle, 1, 0);
  48690. this._appendParticleVertex(offset++, particle, 1, 1);
  48691. this._appendParticleVertex(offset++, particle, 0, 1);
  48692. };
  48693. /**
  48694. * Rebuilds the particle system.
  48695. */
  48696. ParticleSystem.prototype.rebuild = function () {
  48697. this._createIndexBuffer();
  48698. if (this._vertexBuffer) {
  48699. this._vertexBuffer._rebuild();
  48700. }
  48701. };
  48702. /**
  48703. * Renders the particle system in its current state.
  48704. * @returns the current number of particles.
  48705. */
  48706. ParticleSystem.prototype.render = function () {
  48707. var effect = this._getEffect();
  48708. // Check
  48709. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48710. return 0;
  48711. var engine = this._scene.getEngine();
  48712. // Render
  48713. engine.enableEffect(effect);
  48714. engine.setState(false);
  48715. var viewMatrix = this._scene.getViewMatrix();
  48716. effect.setTexture("diffuseSampler", this.particleTexture);
  48717. effect.setMatrix("view", viewMatrix);
  48718. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48719. if (this._isAnimationSheetEnabled) {
  48720. var baseSize = this.particleTexture.getBaseSize();
  48721. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48722. }
  48723. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48724. if (this._scene.clipPlane) {
  48725. var clipPlane = this._scene.clipPlane;
  48726. var invView = viewMatrix.clone();
  48727. invView.invert();
  48728. effect.setMatrix("invView", invView);
  48729. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48730. }
  48731. // VBOs
  48732. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48733. // Draw order
  48734. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48735. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48736. }
  48737. else {
  48738. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48739. }
  48740. if (this.forceDepthWrite) {
  48741. engine.setDepthWrite(true);
  48742. }
  48743. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48744. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48745. return this._particles.length;
  48746. };
  48747. /**
  48748. * Disposes the particle system and free the associated resources.
  48749. */
  48750. ParticleSystem.prototype.dispose = function () {
  48751. if (this._vertexBuffer) {
  48752. this._vertexBuffer.dispose();
  48753. this._vertexBuffer = null;
  48754. }
  48755. if (this._indexBuffer) {
  48756. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48757. this._indexBuffer = null;
  48758. }
  48759. if (this.particleTexture) {
  48760. this.particleTexture.dispose();
  48761. this.particleTexture = null;
  48762. }
  48763. // Remove from scene
  48764. var index = this._scene.particleSystems.indexOf(this);
  48765. if (index > -1) {
  48766. this._scene.particleSystems.splice(index, 1);
  48767. }
  48768. // Callback
  48769. this.onDisposeObservable.notifyObservers(this);
  48770. this.onDisposeObservable.clear();
  48771. };
  48772. /**
  48773. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  48774. * @param radius The radius of the sphere to emit from
  48775. * @returns the emitter
  48776. */
  48777. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  48778. if (radius === void 0) { radius = 1; }
  48779. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  48780. this.particleEmitterType = particleEmitter;
  48781. return particleEmitter;
  48782. };
  48783. /**
  48784. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  48785. * @param radius The radius of the sphere to emit from
  48786. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  48787. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  48788. * @returns the emitter
  48789. */
  48790. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  48791. if (radius === void 0) { radius = 1; }
  48792. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  48793. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  48794. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  48795. this.particleEmitterType = particleEmitter;
  48796. return particleEmitter;
  48797. };
  48798. /**
  48799. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  48800. * @param radius The radius of the cone to emit from
  48801. * @param angle The base angle of the cone
  48802. * @returns the emitter
  48803. */
  48804. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  48805. if (radius === void 0) { radius = 1; }
  48806. if (angle === void 0) { angle = Math.PI / 4; }
  48807. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  48808. this.particleEmitterType = particleEmitter;
  48809. return particleEmitter;
  48810. };
  48811. // 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.
  48812. /**
  48813. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  48814. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  48815. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48816. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48817. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48818. * @returns the emitter
  48819. */
  48820. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48821. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48822. this.direction1 = direction1;
  48823. this.direction2 = direction2;
  48824. this.minEmitBox = minEmitBox;
  48825. this.maxEmitBox = maxEmitBox;
  48826. this.particleEmitterType = particleEmitter;
  48827. return particleEmitter;
  48828. };
  48829. /**
  48830. * Clones the particle system.
  48831. * @param name The name of the cloned object
  48832. * @param newEmitter The new emitter to use
  48833. * @returns the cloned particle system
  48834. */
  48835. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48836. var custom = null;
  48837. var program = null;
  48838. if (this.customShader != null) {
  48839. program = this.customShader;
  48840. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48841. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48842. }
  48843. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48844. result.customShader = program;
  48845. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48846. if (newEmitter === undefined) {
  48847. newEmitter = this.emitter;
  48848. }
  48849. result.emitter = newEmitter;
  48850. if (this.particleTexture) {
  48851. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48852. }
  48853. if (!this.preventAutoStart) {
  48854. result.start();
  48855. }
  48856. return result;
  48857. };
  48858. /**
  48859. * Serializes the particle system to a JSON object.
  48860. * @returns the JSON object
  48861. */
  48862. ParticleSystem.prototype.serialize = function () {
  48863. var serializationObject = {};
  48864. serializationObject.name = this.name;
  48865. serializationObject.id = this.id;
  48866. // Emitter
  48867. if (this.emitter.position) {
  48868. var emitterMesh = this.emitter;
  48869. serializationObject.emitterId = emitterMesh.id;
  48870. }
  48871. else {
  48872. var emitterPosition = this.emitter;
  48873. serializationObject.emitter = emitterPosition.asArray();
  48874. }
  48875. serializationObject.capacity = this.getCapacity();
  48876. if (this.particleTexture) {
  48877. serializationObject.textureName = this.particleTexture.name;
  48878. }
  48879. // Animations
  48880. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48881. // Particle system
  48882. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48883. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48884. serializationObject.minSize = this.minSize;
  48885. serializationObject.maxSize = this.maxSize;
  48886. serializationObject.minEmitPower = this.minEmitPower;
  48887. serializationObject.maxEmitPower = this.maxEmitPower;
  48888. serializationObject.minLifeTime = this.minLifeTime;
  48889. serializationObject.maxLifeTime = this.maxLifeTime;
  48890. serializationObject.emitRate = this.emitRate;
  48891. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48892. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48893. serializationObject.gravity = this.gravity.asArray();
  48894. serializationObject.direction1 = this.direction1.asArray();
  48895. serializationObject.direction2 = this.direction2.asArray();
  48896. serializationObject.color1 = this.color1.asArray();
  48897. serializationObject.color2 = this.color2.asArray();
  48898. serializationObject.colorDead = this.colorDead.asArray();
  48899. serializationObject.updateSpeed = this.updateSpeed;
  48900. serializationObject.targetStopDuration = this.targetStopDuration;
  48901. serializationObject.textureMask = this.textureMask.asArray();
  48902. serializationObject.blendMode = this.blendMode;
  48903. serializationObject.customShader = this.customShader;
  48904. serializationObject.preventAutoStart = this.preventAutoStart;
  48905. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48906. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48907. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48908. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48909. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48910. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48911. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48912. return serializationObject;
  48913. };
  48914. /**
  48915. * Parses a JSON object to create a particle system.
  48916. * @param parsedParticleSystem The JSON object to parse
  48917. * @param scene The scene to create the particle system in
  48918. * @param rootUrl The root url to use to load external dependencies like texture
  48919. * @returns the Parsed particle system
  48920. */
  48921. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48922. var name = parsedParticleSystem.name;
  48923. var custom = null;
  48924. var program = null;
  48925. if (parsedParticleSystem.customShader) {
  48926. program = parsedParticleSystem.customShader;
  48927. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48928. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48929. }
  48930. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48931. particleSystem.customShader = program;
  48932. if (parsedParticleSystem.id) {
  48933. particleSystem.id = parsedParticleSystem.id;
  48934. }
  48935. // Auto start
  48936. if (parsedParticleSystem.preventAutoStart) {
  48937. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48938. }
  48939. // Texture
  48940. if (parsedParticleSystem.textureName) {
  48941. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48942. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48943. }
  48944. // Emitter
  48945. if (parsedParticleSystem.emitterId) {
  48946. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48947. }
  48948. else {
  48949. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48950. }
  48951. // Animations
  48952. if (parsedParticleSystem.animations) {
  48953. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48954. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48955. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48956. }
  48957. }
  48958. if (parsedParticleSystem.autoAnimate) {
  48959. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48960. }
  48961. // Particle system
  48962. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48963. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48964. particleSystem.minSize = parsedParticleSystem.minSize;
  48965. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48966. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48967. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48968. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48969. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48970. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48971. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48972. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48973. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48974. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48975. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48976. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48977. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48978. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48979. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48980. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48981. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48982. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48983. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48984. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48985. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48986. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48987. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48988. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48989. if (!particleSystem.preventAutoStart) {
  48990. particleSystem.start();
  48991. }
  48992. return particleSystem;
  48993. };
  48994. /**
  48995. * Source color is added to the destination color without alpha affecting the result.
  48996. */
  48997. ParticleSystem.BLENDMODE_ONEONE = 0;
  48998. /**
  48999. * Blend current color and particle color using particle’s alpha.
  49000. */
  49001. ParticleSystem.BLENDMODE_STANDARD = 1;
  49002. return ParticleSystem;
  49003. }());
  49004. BABYLON.ParticleSystem = ParticleSystem;
  49005. })(BABYLON || (BABYLON = {}));
  49006. //# sourceMappingURL=babylon.particleSystem.js.map
  49007. var BABYLON;
  49008. (function (BABYLON) {
  49009. /**
  49010. * Particle emitter emitting particles from the inside of a box.
  49011. * It emits the particles randomly between 2 given directions.
  49012. */
  49013. var BoxParticleEmitter = /** @class */ (function () {
  49014. // to be updated like the rest of emitters when breaking changes.
  49015. // all property should be come public variables and passed through constructor.
  49016. /**
  49017. * Creates a new instance of @see BoxParticleEmitter
  49018. * @param _particleSystem the particle system associated with the emitter
  49019. */
  49020. function BoxParticleEmitter(_particleSystem) {
  49021. this._particleSystem = _particleSystem;
  49022. }
  49023. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  49024. /**
  49025. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49026. */
  49027. get: function () {
  49028. return this._particleSystem.direction1;
  49029. },
  49030. /**
  49031. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49032. */
  49033. set: function (value) {
  49034. this._particleSystem.direction1 = value;
  49035. },
  49036. enumerable: true,
  49037. configurable: true
  49038. });
  49039. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  49040. /**
  49041. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49042. */
  49043. get: function () {
  49044. return this._particleSystem.direction2;
  49045. },
  49046. /**
  49047. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49048. */
  49049. set: function (value) {
  49050. this._particleSystem.direction2 = value;
  49051. },
  49052. enumerable: true,
  49053. configurable: true
  49054. });
  49055. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  49056. /**
  49057. * 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.
  49058. */
  49059. get: function () {
  49060. return this._particleSystem.minEmitBox;
  49061. },
  49062. /**
  49063. * 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.
  49064. */
  49065. set: function (value) {
  49066. this._particleSystem.minEmitBox = value;
  49067. },
  49068. enumerable: true,
  49069. configurable: true
  49070. });
  49071. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  49072. /**
  49073. * 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.
  49074. */
  49075. get: function () {
  49076. return this._particleSystem.maxEmitBox;
  49077. },
  49078. /**
  49079. * 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.
  49080. */
  49081. set: function (value) {
  49082. this._particleSystem.maxEmitBox = value;
  49083. },
  49084. enumerable: true,
  49085. configurable: true
  49086. });
  49087. /**
  49088. * Called by the particle System when the direction is computed for the created particle.
  49089. * @param emitPower is the power of the particle (speed)
  49090. * @param worldMatrix is the world matrix of the particle system
  49091. * @param directionToUpdate is the direction vector to update with the result
  49092. * @param particle is the particle we are computed the direction for
  49093. */
  49094. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49095. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49096. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49097. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49098. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49099. };
  49100. /**
  49101. * Called by the particle System when the position is computed for the created particle.
  49102. * @param worldMatrix is the world matrix of the particle system
  49103. * @param positionToUpdate is the position vector to update with the result
  49104. * @param particle is the particle we are computed the position for
  49105. */
  49106. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49107. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  49108. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  49109. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  49110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49111. };
  49112. /**
  49113. * Clones the current emitter and returns a copy of it
  49114. * @returns the new emitter
  49115. */
  49116. BoxParticleEmitter.prototype.clone = function () {
  49117. var newOne = new BoxParticleEmitter(this._particleSystem);
  49118. BABYLON.Tools.DeepCopy(this, newOne);
  49119. return newOne;
  49120. };
  49121. return BoxParticleEmitter;
  49122. }());
  49123. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  49124. })(BABYLON || (BABYLON = {}));
  49125. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  49126. var BABYLON;
  49127. (function (BABYLON) {
  49128. /**
  49129. * Particle emitter emitting particles from the inside of a cone.
  49130. * It emits the particles alongside the cone volume from the base to the particle.
  49131. * The emission direction might be randomized.
  49132. */
  49133. var ConeParticleEmitter = /** @class */ (function () {
  49134. /**
  49135. * Creates a new instance of @see ConeParticleEmitter
  49136. * @param radius the radius of the emission cone
  49137. * @param angles the cone base angle
  49138. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49139. */
  49140. function ConeParticleEmitter(radius,
  49141. /**
  49142. * The radius of the emission cone.
  49143. */
  49144. angle,
  49145. /**
  49146. * The cone base angle.
  49147. */
  49148. directionRandomizer) {
  49149. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49150. this.angle = angle;
  49151. this.directionRandomizer = directionRandomizer;
  49152. this.radius = radius;
  49153. }
  49154. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  49155. /**
  49156. * Gets the radius of the emission cone.
  49157. */
  49158. get: function () {
  49159. return this._radius;
  49160. },
  49161. /**
  49162. * Sets the radius of the emission cone.
  49163. */
  49164. set: function (value) {
  49165. this._radius = value;
  49166. if (this.angle !== 0) {
  49167. this._height = value / Math.tan(this.angle / 2);
  49168. }
  49169. else {
  49170. this._height = 1;
  49171. }
  49172. },
  49173. enumerable: true,
  49174. configurable: true
  49175. });
  49176. /**
  49177. * Called by the particle System when the direction is computed for the created particle.
  49178. * @param emitPower is the power of the particle (speed)
  49179. * @param worldMatrix is the world matrix of the particle system
  49180. * @param directionToUpdate is the direction vector to update with the result
  49181. * @param particle is the particle we are computed the direction for
  49182. */
  49183. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49184. if (this.angle === 0) {
  49185. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  49186. }
  49187. else {
  49188. // measure the direction Vector from the emitter to the particle.
  49189. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49190. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49191. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49192. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49193. direction.x += randX;
  49194. direction.y += randY;
  49195. direction.z += randZ;
  49196. direction.normalize();
  49197. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49198. }
  49199. };
  49200. /**
  49201. * Called by the particle System when the position is computed for the created particle.
  49202. * @param worldMatrix is the world matrix of the particle system
  49203. * @param positionToUpdate is the position vector to update with the result
  49204. * @param particle is the particle we are computed the position for
  49205. */
  49206. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49207. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  49208. var h = BABYLON.Scalar.RandomRange(0, 1);
  49209. // Better distribution in a cone at normal angles.
  49210. h = 1 - h * h;
  49211. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  49212. radius = radius * h / this._height;
  49213. var randX = radius * Math.sin(s);
  49214. var randZ = radius * Math.cos(s);
  49215. var randY = h;
  49216. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49217. };
  49218. /**
  49219. * Clones the current emitter and returns a copy of it
  49220. * @returns the new emitter
  49221. */
  49222. ConeParticleEmitter.prototype.clone = function () {
  49223. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  49224. BABYLON.Tools.DeepCopy(this, newOne);
  49225. return newOne;
  49226. };
  49227. return ConeParticleEmitter;
  49228. }());
  49229. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  49230. })(BABYLON || (BABYLON = {}));
  49231. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  49232. var BABYLON;
  49233. (function (BABYLON) {
  49234. /**
  49235. * Particle emitter emitting particles from the inside of a sphere.
  49236. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  49237. */
  49238. var SphereParticleEmitter = /** @class */ (function () {
  49239. /**
  49240. * Creates a new instance of @see SphereParticleEmitter
  49241. * @param radius the radius of the emission sphere
  49242. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49243. */
  49244. function SphereParticleEmitter(
  49245. /**
  49246. * The radius of the emission sphere.
  49247. */
  49248. radius,
  49249. /**
  49250. * How much to randomize the particle direction [0-1].
  49251. */
  49252. directionRandomizer) {
  49253. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49254. this.radius = radius;
  49255. this.directionRandomizer = directionRandomizer;
  49256. }
  49257. /**
  49258. * Called by the particle System when the direction is computed for the created particle.
  49259. * @param emitPower is the power of the particle (speed)
  49260. * @param worldMatrix is the world matrix of the particle system
  49261. * @param directionToUpdate is the direction vector to update with the result
  49262. * @param particle is the particle we are computed the direction for
  49263. */
  49264. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49265. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49266. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49267. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49268. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49269. direction.x += randX;
  49270. direction.y += randY;
  49271. direction.z += randZ;
  49272. direction.normalize();
  49273. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49274. };
  49275. /**
  49276. * Called by the particle System when the position is computed for the created particle.
  49277. * @param worldMatrix is the world matrix of the particle system
  49278. * @param positionToUpdate is the position vector to update with the result
  49279. * @param particle is the particle we are computed the position for
  49280. */
  49281. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49282. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  49283. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  49284. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  49285. var randY = this.radius * Math.cos(theta);
  49286. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  49287. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49288. };
  49289. /**
  49290. * Clones the current emitter and returns a copy of it
  49291. * @returns the new emitter
  49292. */
  49293. SphereParticleEmitter.prototype.clone = function () {
  49294. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  49295. BABYLON.Tools.DeepCopy(this, newOne);
  49296. return newOne;
  49297. };
  49298. return SphereParticleEmitter;
  49299. }());
  49300. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  49301. /**
  49302. * Particle emitter emitting particles from the inside of a sphere.
  49303. * It emits the particles randomly between two vectors.
  49304. */
  49305. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  49306. __extends(SphereDirectedParticleEmitter, _super);
  49307. /**
  49308. * Creates a new instance of @see SphereDirectedParticleEmitter
  49309. * @param radius the radius of the emission sphere
  49310. * @param direction1 the min limit of the emission direction
  49311. * @param direction2 the max limit of the emission direction
  49312. */
  49313. function SphereDirectedParticleEmitter(radius,
  49314. /**
  49315. * The min limit of the emission direction.
  49316. */
  49317. direction1,
  49318. /**
  49319. * The max limit of the emission direction.
  49320. */
  49321. direction2) {
  49322. var _this = _super.call(this, radius) || this;
  49323. _this.direction1 = direction1;
  49324. _this.direction2 = direction2;
  49325. return _this;
  49326. }
  49327. /**
  49328. * Called by the particle System when the direction is computed for the created particle.
  49329. * @param emitPower is the power of the particle (speed)
  49330. * @param worldMatrix is the world matrix of the particle system
  49331. * @param directionToUpdate is the direction vector to update with the result
  49332. * @param particle is the particle we are computed the direction for
  49333. */
  49334. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49335. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49336. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49337. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49338. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49339. };
  49340. /**
  49341. * Clones the current emitter and returns a copy of it
  49342. * @returns the new emitter
  49343. */
  49344. SphereDirectedParticleEmitter.prototype.clone = function () {
  49345. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  49346. BABYLON.Tools.DeepCopy(this, newOne);
  49347. return newOne;
  49348. };
  49349. return SphereDirectedParticleEmitter;
  49350. }(SphereParticleEmitter));
  49351. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  49352. })(BABYLON || (BABYLON = {}));
  49353. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  49354. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  49355. var BABYLON;
  49356. (function (BABYLON) {
  49357. /**
  49358. * This represents a GPU particle system in Babylon.
  49359. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  49360. */
  49361. var GPUParticleSystem = /** @class */ (function () {
  49362. /**
  49363. * Instantiates a GPU particle system.
  49364. * 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.
  49365. * @param name The name of the particle system
  49366. * @param capacity The max number of particles alive at the same time
  49367. * @param scene The scene the particle system belongs to
  49368. */
  49369. function GPUParticleSystem(name, capacity, scene) {
  49370. /**
  49371. * The emitter represents the Mesh or position we are attaching the particle system to.
  49372. */
  49373. this.emitter = null;
  49374. /**
  49375. * The rendering group used by the Particle system to chose when to render.
  49376. */
  49377. this.renderingGroupId = 0;
  49378. /**
  49379. * The layer mask we are rendering the particles through.
  49380. */
  49381. this.layerMask = 0x0FFFFFFF; // TODO
  49382. this._updateVertexBuffers = {};
  49383. this._renderVertexBuffers = {};
  49384. this._currentRenderId = -1;
  49385. this._started = true;
  49386. /**
  49387. * An event triggered when the system is disposed.
  49388. */
  49389. this.onDisposeObservable = new BABYLON.Observable();
  49390. this.id = name;
  49391. this.name = name;
  49392. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49393. this._capacity = capacity;
  49394. this._engine = this._scene.getEngine();
  49395. this._scene.particleSystems.push(this);
  49396. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  49397. var updateEffectOptions = {
  49398. attributes: ["position", "age", "life", "velocity"],
  49399. uniformsNames: [],
  49400. uniformBuffersNames: [],
  49401. samplers: [],
  49402. defines: "",
  49403. fallbacks: null,
  49404. onCompiled: null,
  49405. onError: null,
  49406. indexParameters: null,
  49407. maxSimultaneousLights: 0,
  49408. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  49409. };
  49410. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  49411. }
  49412. /**
  49413. * Gets Wether the system has been started.
  49414. * @returns True if it has been started, otherwise false.
  49415. */
  49416. GPUParticleSystem.prototype.isStarted = function () {
  49417. return this._started;
  49418. };
  49419. /**
  49420. * Starts the particle system and begins to emit.
  49421. */
  49422. GPUParticleSystem.prototype.start = function () {
  49423. this._started = true;
  49424. };
  49425. /**
  49426. * Stops the particle system.
  49427. */
  49428. GPUParticleSystem.prototype.stop = function () {
  49429. this._started = false;
  49430. };
  49431. /**
  49432. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  49433. */
  49434. GPUParticleSystem.prototype.animate = function () {
  49435. // Do nothing
  49436. };
  49437. GPUParticleSystem.prototype._initialize = function () {
  49438. if (this._renderVAO) {
  49439. return;
  49440. }
  49441. var data = new Array();
  49442. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  49443. // position
  49444. data.push(0.0);
  49445. data.push(0.0);
  49446. data.push(0.0);
  49447. var life = 1 + Math.random() * 10; // TODO: var
  49448. data.push(life + 1); // create the particle as a dead one to create a new one at start
  49449. data.push(life);
  49450. // velocity
  49451. data.push(0.0);
  49452. data.push(0.0);
  49453. data.push(0.0);
  49454. }
  49455. // Update VAO
  49456. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  49457. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  49458. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  49459. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  49460. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  49461. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  49462. this._engine.bindArrayBuffer(null);
  49463. // Render VAO
  49464. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  49465. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  49466. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  49467. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  49468. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  49469. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  49470. this._engine.bindArrayBuffer(null);
  49471. // Links
  49472. this._sourceVAO = this._updateVAO;
  49473. this._targetVAO = this._renderVAO;
  49474. this._sourceBuffer = this._updateBuffer;
  49475. this._targetBuffer = this._renderBuffer;
  49476. };
  49477. /**
  49478. * Renders the particle system in its current state.
  49479. * @returns the current number of particles.
  49480. */
  49481. GPUParticleSystem.prototype.render = function () {
  49482. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  49483. return 0;
  49484. }
  49485. // Get everything ready to render
  49486. this._initialize();
  49487. if (this._currentRenderId === this._scene.getRenderId()) {
  49488. return 0;
  49489. }
  49490. this._currentRenderId = this._scene.getRenderId();
  49491. // Enable update effect
  49492. this._engine.enableEffect(this._updateEffect);
  49493. this._engine.setState(false);
  49494. // Bind source VAO
  49495. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  49496. // Update
  49497. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  49498. this._engine.setRasterizerState(false);
  49499. this._engine.beginTransformFeedback();
  49500. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  49501. this._engine.endTransformFeedback();
  49502. this._engine.setRasterizerState(true);
  49503. this._engine.bindTransformFeedbackBuffer(null);
  49504. // Enable render effect
  49505. this._engine.enableEffect(this._renderEffect);
  49506. // Bind source VAO
  49507. this._engine.bindVertexArrayObject(this._targetVAO, null);
  49508. // Render
  49509. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  49510. // Switch VAOs
  49511. var tmpVAO = this._sourceVAO;
  49512. this._sourceVAO = this._targetVAO;
  49513. this._targetVAO = tmpVAO;
  49514. // Switch buffers
  49515. var tmpBuffer = this._sourceBuffer;
  49516. this._sourceBuffer = this._targetBuffer;
  49517. this._targetBuffer = tmpBuffer;
  49518. return 0;
  49519. };
  49520. /**
  49521. * Rebuilds the particle system
  49522. */
  49523. GPUParticleSystem.prototype.rebuild = function () {
  49524. };
  49525. /**
  49526. * Disposes the particle system and free the associated resources.
  49527. */
  49528. GPUParticleSystem.prototype.dispose = function () {
  49529. var index = this._scene.particleSystems.indexOf(this);
  49530. if (index > -1) {
  49531. this._scene.particleSystems.splice(index, 1);
  49532. }
  49533. //TODO: this._dataBuffer.dispose();
  49534. // Callback
  49535. this.onDisposeObservable.notifyObservers(this);
  49536. this.onDisposeObservable.clear();
  49537. };
  49538. //TODO: Clone / Parse / serialize
  49539. /**
  49540. * Clones the particle system.
  49541. * @param name The name of the cloned object
  49542. * @param newEmitter The new emitter to use
  49543. * @returns the cloned particle system
  49544. */
  49545. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  49546. return null;
  49547. };
  49548. /**
  49549. * Serializes the particle system to a JSON object.
  49550. * @returns the JSON object
  49551. */
  49552. GPUParticleSystem.prototype.serialize = function () {
  49553. };
  49554. return GPUParticleSystem;
  49555. }());
  49556. BABYLON.GPUParticleSystem = GPUParticleSystem;
  49557. })(BABYLON || (BABYLON = {}));
  49558. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  49559. var BABYLON;
  49560. (function (BABYLON) {
  49561. /**
  49562. * Represents one particle of a solid particle system.
  49563. * @see SolidParticleSystem
  49564. */
  49565. var SolidParticle = /** @class */ (function () {
  49566. /**
  49567. * Creates a Solid Particle object.
  49568. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49569. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49570. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49571. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49572. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49573. * @param shapeId (integer) is the model shape identifier in the SPS.
  49574. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49575. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49576. */
  49577. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49578. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49579. /**
  49580. * particle global index
  49581. */
  49582. this.idx = 0;
  49583. /**
  49584. * The color of the particle
  49585. */
  49586. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49587. /**
  49588. * The world space position of the particle.
  49589. */
  49590. this.position = BABYLON.Vector3.Zero();
  49591. /**
  49592. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49593. */
  49594. this.rotation = BABYLON.Vector3.Zero();
  49595. /**
  49596. * The scaling of the particle.
  49597. */
  49598. this.scaling = BABYLON.Vector3.One();
  49599. /**
  49600. * The uvs of the particle.
  49601. */
  49602. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49603. /**
  49604. * The current speed of the particle.
  49605. */
  49606. this.velocity = BABYLON.Vector3.Zero();
  49607. /**
  49608. * The pivot point in the particle local space.
  49609. */
  49610. this.pivot = BABYLON.Vector3.Zero();
  49611. /**
  49612. * Is the particle active or not ?
  49613. */
  49614. this.alive = true;
  49615. /**
  49616. * Is the particle visible or not ?
  49617. */
  49618. this.isVisible = true;
  49619. /**
  49620. * Index of this particle in the global "positions" array (Internal use)
  49621. */
  49622. this._pos = 0;
  49623. /**
  49624. * Index of this particle in the global "indices" array (Internal use)
  49625. */
  49626. this._ind = 0;
  49627. /**
  49628. * ModelShape id of this particle
  49629. */
  49630. this.shapeId = 0;
  49631. /**
  49632. * Index of the particle in its shape id (Internal use)
  49633. */
  49634. this.idxInShape = 0;
  49635. /**
  49636. * Still set as invisible in order to skip useless computations (Internal use)
  49637. */
  49638. this._stillInvisible = false;
  49639. /**
  49640. * Last computed particle rotation matrix
  49641. */
  49642. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  49643. this.idx = particleIndex;
  49644. this._pos = positionIndex;
  49645. this._ind = indiceIndex;
  49646. this._model = model;
  49647. this.shapeId = shapeId;
  49648. this.idxInShape = idxInShape;
  49649. this._sps = sps;
  49650. if (modelBoundingInfo) {
  49651. this._modelBoundingInfo = modelBoundingInfo;
  49652. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49653. }
  49654. }
  49655. Object.defineProperty(SolidParticle.prototype, "scale", {
  49656. /**
  49657. * Legacy support, changed scale to scaling
  49658. */
  49659. get: function () {
  49660. return this.scaling;
  49661. },
  49662. /**
  49663. * Legacy support, changed scale to scaling
  49664. */
  49665. set: function (scale) {
  49666. this.scaling = scale;
  49667. },
  49668. enumerable: true,
  49669. configurable: true
  49670. });
  49671. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49672. /**
  49673. * Legacy support, changed quaternion to rotationQuaternion
  49674. */
  49675. get: function () {
  49676. return this.rotationQuaternion;
  49677. },
  49678. /**
  49679. * Legacy support, changed quaternion to rotationQuaternion
  49680. */
  49681. set: function (q) {
  49682. this.rotationQuaternion = q;
  49683. },
  49684. enumerable: true,
  49685. configurable: true
  49686. });
  49687. /**
  49688. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49689. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49690. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49691. * @returns true if it intersects
  49692. */
  49693. SolidParticle.prototype.intersectsMesh = function (target) {
  49694. if (!this._boundingInfo || !target._boundingInfo) {
  49695. return false;
  49696. }
  49697. if (this._sps._bSphereOnly) {
  49698. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49699. }
  49700. return this._boundingInfo.intersects(target._boundingInfo, false);
  49701. };
  49702. return SolidParticle;
  49703. }());
  49704. BABYLON.SolidParticle = SolidParticle;
  49705. /**
  49706. * Represents the shape of the model used by one particle of a solid particle system.
  49707. * SPS internal tool, don't use it manually.
  49708. * @see SolidParticleSystem
  49709. */
  49710. var ModelShape = /** @class */ (function () {
  49711. /**
  49712. * 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.
  49713. * SPS internal tool, don't use it manually.
  49714. * @ignore
  49715. */
  49716. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49717. /**
  49718. * length of the shape in the model indices array (internal use)
  49719. */
  49720. this._indicesLength = 0;
  49721. this.shapeID = id;
  49722. this._shape = shape;
  49723. this._indicesLength = indicesLength;
  49724. this._shapeUV = shapeUV;
  49725. this._positionFunction = posFunction;
  49726. this._vertexFunction = vtxFunction;
  49727. }
  49728. return ModelShape;
  49729. }());
  49730. BABYLON.ModelShape = ModelShape;
  49731. /**
  49732. * Represents a Depth Sorted Particle in the solid particle system.
  49733. * @see SolidParticleSystem
  49734. */
  49735. var DepthSortedParticle = /** @class */ (function () {
  49736. function DepthSortedParticle() {
  49737. /**
  49738. * Index of the particle in the "indices" array
  49739. */
  49740. this.ind = 0;
  49741. /**
  49742. * Length of the particle shape in the "indices" array
  49743. */
  49744. this.indicesLength = 0;
  49745. /**
  49746. * Squared distance from the particle to the camera
  49747. */
  49748. this.sqDistance = 0.0;
  49749. }
  49750. return DepthSortedParticle;
  49751. }());
  49752. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49753. })(BABYLON || (BABYLON = {}));
  49754. //# sourceMappingURL=babylon.solidParticle.js.map
  49755. var BABYLON;
  49756. (function (BABYLON) {
  49757. /**
  49758. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49759. *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.
  49760. * The SPS is also a particle system. It provides some methods to manage the particles.
  49761. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49762. *
  49763. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49764. */
  49765. var SolidParticleSystem = /** @class */ (function () {
  49766. /**
  49767. * Creates a SPS (Solid Particle System) object.
  49768. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49769. * @param scene (Scene) is the scene in which the SPS is added.
  49770. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49771. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49772. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49773. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49774. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49775. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49776. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49777. */
  49778. function SolidParticleSystem(name, scene, options) {
  49779. /**
  49780. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49781. * Example : var p = SPS.particles[i];
  49782. */
  49783. this.particles = new Array();
  49784. /**
  49785. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49786. */
  49787. this.nbParticles = 0;
  49788. /**
  49789. * If the particles must ever face the camera (default false). Useful for planar particles.
  49790. */
  49791. this.billboard = false;
  49792. /**
  49793. * Recompute normals when adding a shape
  49794. */
  49795. this.recomputeNormals = true;
  49796. /**
  49797. * This a counter ofr your own usage. It's not set by any SPS functions.
  49798. */
  49799. this.counter = 0;
  49800. /**
  49801. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49802. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49803. */
  49804. this.vars = {};
  49805. /**
  49806. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49807. */
  49808. this._bSphereOnly = false;
  49809. /**
  49810. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49811. */
  49812. this._bSphereRadiusFactor = 1.0;
  49813. this._positions = new Array();
  49814. this._indices = new Array();
  49815. this._normals = new Array();
  49816. this._colors = new Array();
  49817. this._uvs = new Array();
  49818. this._index = 0; // indices index
  49819. this._updatable = true;
  49820. this._pickable = false;
  49821. this._isVisibilityBoxLocked = false;
  49822. this._alwaysVisible = false;
  49823. this._depthSort = false;
  49824. this._shapeCounter = 0;
  49825. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49826. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49827. this._computeParticleColor = true;
  49828. this._computeParticleTexture = true;
  49829. this._computeParticleRotation = true;
  49830. this._computeParticleVertex = false;
  49831. this._computeBoundingBox = false;
  49832. this._depthSortParticles = true;
  49833. this._cam_axisZ = BABYLON.Vector3.Zero();
  49834. this._cam_axisY = BABYLON.Vector3.Zero();
  49835. this._cam_axisX = BABYLON.Vector3.Zero();
  49836. this._axisZ = BABYLON.Axis.Z;
  49837. this._camDir = BABYLON.Vector3.Zero();
  49838. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49839. this._rotMatrix = new BABYLON.Matrix();
  49840. this._invertMatrix = new BABYLON.Matrix();
  49841. this._rotated = BABYLON.Vector3.Zero();
  49842. this._quaternion = new BABYLON.Quaternion();
  49843. this._vertex = BABYLON.Vector3.Zero();
  49844. this._normal = BABYLON.Vector3.Zero();
  49845. this._yaw = 0.0;
  49846. this._pitch = 0.0;
  49847. this._roll = 0.0;
  49848. this._halfroll = 0.0;
  49849. this._halfpitch = 0.0;
  49850. this._halfyaw = 0.0;
  49851. this._sinRoll = 0.0;
  49852. this._cosRoll = 0.0;
  49853. this._sinPitch = 0.0;
  49854. this._cosPitch = 0.0;
  49855. this._sinYaw = 0.0;
  49856. this._cosYaw = 0.0;
  49857. this._mustUnrotateFixedNormals = false;
  49858. this._minimum = BABYLON.Tmp.Vector3[0];
  49859. this._maximum = BABYLON.Tmp.Vector3[1];
  49860. this._minBbox = BABYLON.Tmp.Vector3[4];
  49861. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49862. this._particlesIntersect = false;
  49863. this._depthSortFunction = function (p1, p2) {
  49864. return (p2.sqDistance - p1.sqDistance);
  49865. };
  49866. this._needs32Bits = false;
  49867. this.name = name;
  49868. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49869. this._camera = scene.activeCamera;
  49870. this._pickable = options ? options.isPickable : false;
  49871. this._depthSort = options ? options.enableDepthSort : false;
  49872. this._particlesIntersect = options ? options.particleIntersection : false;
  49873. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49874. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49875. if (options && options.updatable) {
  49876. this._updatable = options.updatable;
  49877. }
  49878. else {
  49879. this._updatable = true;
  49880. }
  49881. if (this._pickable) {
  49882. this.pickedParticles = [];
  49883. }
  49884. if (this._depthSort) {
  49885. this.depthSortedParticles = [];
  49886. }
  49887. }
  49888. /**
  49889. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49890. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49891. * @returns the created mesh
  49892. */
  49893. SolidParticleSystem.prototype.buildMesh = function () {
  49894. if (this.nbParticles === 0) {
  49895. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49896. this.addShape(triangle, 1);
  49897. triangle.dispose();
  49898. }
  49899. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49900. this._positions32 = new Float32Array(this._positions);
  49901. this._uvs32 = new Float32Array(this._uvs);
  49902. this._colors32 = new Float32Array(this._colors);
  49903. if (this.recomputeNormals) {
  49904. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49905. }
  49906. this._normals32 = new Float32Array(this._normals);
  49907. this._fixedNormal32 = new Float32Array(this._normals);
  49908. if (this._mustUnrotateFixedNormals) {
  49909. this._unrotateFixedNormals();
  49910. }
  49911. var vertexData = new BABYLON.VertexData();
  49912. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49913. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49914. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49915. if (this._uvs32) {
  49916. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49917. ;
  49918. }
  49919. if (this._colors32) {
  49920. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49921. }
  49922. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49923. vertexData.applyToMesh(mesh, this._updatable);
  49924. this.mesh = mesh;
  49925. this.mesh.isPickable = this._pickable;
  49926. // free memory
  49927. if (!this._depthSort) {
  49928. this._indices = null;
  49929. }
  49930. this._positions = null;
  49931. this._normals = null;
  49932. this._uvs = null;
  49933. this._colors = null;
  49934. if (!this._updatable) {
  49935. this.particles.length = 0;
  49936. }
  49937. return mesh;
  49938. };
  49939. /**
  49940. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49941. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49942. * Thus the particles generated from `digest()` have their property `position` set yet.
  49943. * @param mesh ( Mesh ) is the mesh to be digested
  49944. * @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
  49945. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49946. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49947. * @returns the current SPS
  49948. */
  49949. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49950. var size = (options && options.facetNb) || 1;
  49951. var number = (options && options.number) || 0;
  49952. var delta = (options && options.delta) || 0;
  49953. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49954. var meshInd = mesh.getIndices();
  49955. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49956. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49957. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49958. var f = 0; // facet counter
  49959. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49960. // compute size from number
  49961. if (number) {
  49962. number = (number > totalFacets) ? totalFacets : number;
  49963. size = Math.round(totalFacets / number);
  49964. delta = 0;
  49965. }
  49966. else {
  49967. size = (size > totalFacets) ? totalFacets : size;
  49968. }
  49969. var facetPos = []; // submesh positions
  49970. var facetInd = []; // submesh indices
  49971. var facetUV = []; // submesh UV
  49972. var facetCol = []; // submesh colors
  49973. var barycenter = BABYLON.Tmp.Vector3[0];
  49974. var sizeO = size;
  49975. while (f < totalFacets) {
  49976. size = sizeO + Math.floor((1 + delta) * Math.random());
  49977. if (f > totalFacets - size) {
  49978. size = totalFacets - f;
  49979. }
  49980. // reset temp arrays
  49981. facetPos.length = 0;
  49982. facetInd.length = 0;
  49983. facetUV.length = 0;
  49984. facetCol.length = 0;
  49985. // iterate over "size" facets
  49986. var fi = 0;
  49987. for (var j = f * 3; j < (f + size) * 3; j++) {
  49988. facetInd.push(fi);
  49989. var i = meshInd[j];
  49990. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49991. if (meshUV) {
  49992. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49993. }
  49994. if (meshCol) {
  49995. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49996. }
  49997. fi++;
  49998. }
  49999. // create a model shape for each single particle
  50000. var idx = this.nbParticles;
  50001. var shape = this._posToShape(facetPos);
  50002. var shapeUV = this._uvsToShapeUV(facetUV);
  50003. // compute the barycenter of the shape
  50004. var v;
  50005. for (v = 0; v < shape.length; v++) {
  50006. barycenter.addInPlace(shape[v]);
  50007. }
  50008. barycenter.scaleInPlace(1 / shape.length);
  50009. // shift the shape from its barycenter to the origin
  50010. for (v = 0; v < shape.length; v++) {
  50011. shape[v].subtractInPlace(barycenter);
  50012. }
  50013. var bInfo;
  50014. if (this._particlesIntersect) {
  50015. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  50016. }
  50017. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  50018. // add the particle in the SPS
  50019. var currentPos = this._positions.length;
  50020. var currentInd = this._indices.length;
  50021. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  50022. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  50023. // initialize the particle position
  50024. this.particles[this.nbParticles].position.addInPlace(barycenter);
  50025. this._index += shape.length;
  50026. idx++;
  50027. this.nbParticles++;
  50028. this._shapeCounter++;
  50029. f += size;
  50030. }
  50031. return this;
  50032. };
  50033. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  50034. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  50035. var index = 0;
  50036. var idx = 0;
  50037. for (var p = 0; p < this.particles.length; p++) {
  50038. this._particle = this.particles[p];
  50039. this._shape = this._particle._model._shape;
  50040. if (this._particle.rotationQuaternion) {
  50041. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50042. }
  50043. else {
  50044. this._yaw = this._particle.rotation.y;
  50045. this._pitch = this._particle.rotation.x;
  50046. this._roll = this._particle.rotation.z;
  50047. this._quaternionRotationYPR();
  50048. }
  50049. this._quaternionToRotationMatrix();
  50050. this._rotMatrix.invertToRef(this._invertMatrix);
  50051. for (var pt = 0; pt < this._shape.length; pt++) {
  50052. idx = index + pt * 3;
  50053. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  50054. this._fixedNormal32[idx] = this._normal.x;
  50055. this._fixedNormal32[idx + 1] = this._normal.y;
  50056. this._fixedNormal32[idx + 2] = this._normal.z;
  50057. }
  50058. index = idx + 3;
  50059. }
  50060. };
  50061. //reset copy
  50062. SolidParticleSystem.prototype._resetCopy = function () {
  50063. this._copy.position.x = 0;
  50064. this._copy.position.y = 0;
  50065. this._copy.position.z = 0;
  50066. this._copy.rotation.x = 0;
  50067. this._copy.rotation.y = 0;
  50068. this._copy.rotation.z = 0;
  50069. this._copy.rotationQuaternion = null;
  50070. this._copy.scaling.x = 1.0;
  50071. this._copy.scaling.y = 1.0;
  50072. this._copy.scaling.z = 1.0;
  50073. this._copy.uvs.x = 0;
  50074. this._copy.uvs.y = 0;
  50075. this._copy.uvs.z = 1.0;
  50076. this._copy.uvs.w = 1.0;
  50077. this._copy.color = null;
  50078. };
  50079. // _meshBuilder : inserts the shape model in the global SPS mesh
  50080. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  50081. var i;
  50082. var u = 0;
  50083. var c = 0;
  50084. var n = 0;
  50085. this._resetCopy();
  50086. if (options && options.positionFunction) {
  50087. options.positionFunction(this._copy, idx, idxInShape);
  50088. this._mustUnrotateFixedNormals = true;
  50089. }
  50090. if (this._copy.rotationQuaternion) {
  50091. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50092. }
  50093. else {
  50094. this._yaw = this._copy.rotation.y;
  50095. this._pitch = this._copy.rotation.x;
  50096. this._roll = this._copy.rotation.z;
  50097. this._quaternionRotationYPR();
  50098. }
  50099. this._quaternionToRotationMatrix();
  50100. for (i = 0; i < shape.length; i++) {
  50101. this._vertex.x = shape[i].x;
  50102. this._vertex.y = shape[i].y;
  50103. this._vertex.z = shape[i].z;
  50104. if (options && options.vertexFunction) {
  50105. options.vertexFunction(this._copy, this._vertex, i);
  50106. }
  50107. this._vertex.x *= this._copy.scaling.x;
  50108. this._vertex.y *= this._copy.scaling.y;
  50109. this._vertex.z *= this._copy.scaling.z;
  50110. this._vertex.x += this._copy.pivot.x;
  50111. this._vertex.y += this._copy.pivot.y;
  50112. this._vertex.z += this._copy.pivot.z;
  50113. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50114. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50115. if (meshUV) {
  50116. 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);
  50117. u += 2;
  50118. }
  50119. if (this._copy.color) {
  50120. this._color = this._copy.color;
  50121. }
  50122. else if (meshCol && meshCol[c] !== undefined) {
  50123. this._color.r = meshCol[c];
  50124. this._color.g = meshCol[c + 1];
  50125. this._color.b = meshCol[c + 2];
  50126. this._color.a = meshCol[c + 3];
  50127. }
  50128. else {
  50129. this._color.r = 1.0;
  50130. this._color.g = 1.0;
  50131. this._color.b = 1.0;
  50132. this._color.a = 1.0;
  50133. }
  50134. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50135. c += 4;
  50136. if (!this.recomputeNormals && meshNor) {
  50137. this._normal.x = meshNor[n];
  50138. this._normal.y = meshNor[n + 1];
  50139. this._normal.z = meshNor[n + 2];
  50140. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  50141. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50142. n += 3;
  50143. }
  50144. }
  50145. for (i = 0; i < meshInd.length; i++) {
  50146. var current_ind = p + meshInd[i];
  50147. indices.push(current_ind);
  50148. if (current_ind > 65535) {
  50149. this._needs32Bits = true;
  50150. }
  50151. }
  50152. if (this._pickable) {
  50153. var nbfaces = meshInd.length / 3;
  50154. for (i = 0; i < nbfaces; i++) {
  50155. this.pickedParticles.push({ idx: idx, faceId: i });
  50156. }
  50157. }
  50158. if (this._depthSort) {
  50159. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  50160. }
  50161. return this._copy;
  50162. };
  50163. // returns a shape array from positions array
  50164. SolidParticleSystem.prototype._posToShape = function (positions) {
  50165. var shape = [];
  50166. for (var i = 0; i < positions.length; i += 3) {
  50167. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50168. }
  50169. return shape;
  50170. };
  50171. // returns a shapeUV array from a Vector4 uvs
  50172. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50173. var shapeUV = [];
  50174. if (uvs) {
  50175. for (var i = 0; i < uvs.length; i++)
  50176. shapeUV.push(uvs[i]);
  50177. }
  50178. return shapeUV;
  50179. };
  50180. // adds a new particle object in the particles array
  50181. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  50182. if (bInfo === void 0) { bInfo = null; }
  50183. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  50184. this.particles.push(sp);
  50185. return sp;
  50186. };
  50187. /**
  50188. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50189. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50190. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  50191. * @param nb (positive integer) the number of particles to be created from this model
  50192. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  50193. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  50194. * @returns the number of shapes in the system
  50195. */
  50196. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50197. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50198. var meshInd = mesh.getIndices();
  50199. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50200. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50201. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50202. var bbInfo;
  50203. if (this._particlesIntersect) {
  50204. bbInfo = mesh.getBoundingInfo();
  50205. }
  50206. var shape = this._posToShape(meshPos);
  50207. var shapeUV = this._uvsToShapeUV(meshUV);
  50208. var posfunc = options ? options.positionFunction : null;
  50209. var vtxfunc = options ? options.vertexFunction : null;
  50210. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  50211. // particles
  50212. var sp;
  50213. var currentCopy;
  50214. var idx = this.nbParticles;
  50215. for (var i = 0; i < nb; i++) {
  50216. var currentPos = this._positions.length;
  50217. var currentInd = this._indices.length;
  50218. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50219. if (this._updatable) {
  50220. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  50221. sp.position.copyFrom(currentCopy.position);
  50222. sp.rotation.copyFrom(currentCopy.rotation);
  50223. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  50224. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  50225. }
  50226. if (currentCopy.color && sp.color) {
  50227. sp.color.copyFrom(currentCopy.color);
  50228. }
  50229. sp.scaling.copyFrom(currentCopy.scaling);
  50230. sp.uvs.copyFrom(currentCopy.uvs);
  50231. }
  50232. this._index += shape.length;
  50233. idx++;
  50234. }
  50235. this.nbParticles += nb;
  50236. this._shapeCounter++;
  50237. return this._shapeCounter - 1;
  50238. };
  50239. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50240. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50241. this._resetCopy();
  50242. if (particle._model._positionFunction) {
  50243. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50244. }
  50245. if (this._copy.rotationQuaternion) {
  50246. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50247. }
  50248. else {
  50249. this._yaw = this._copy.rotation.y;
  50250. this._pitch = this._copy.rotation.x;
  50251. this._roll = this._copy.rotation.z;
  50252. this._quaternionRotationYPR();
  50253. }
  50254. this._quaternionToRotationMatrix();
  50255. this._shape = particle._model._shape;
  50256. for (var pt = 0; pt < this._shape.length; pt++) {
  50257. this._vertex.x = this._shape[pt].x;
  50258. this._vertex.y = this._shape[pt].y;
  50259. this._vertex.z = this._shape[pt].z;
  50260. if (particle._model._vertexFunction) {
  50261. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50262. }
  50263. this._vertex.x *= this._copy.scaling.x;
  50264. this._vertex.y *= this._copy.scaling.y;
  50265. this._vertex.z *= this._copy.scaling.z;
  50266. this._vertex.x += this._copy.pivot.x;
  50267. this._vertex.y += this._copy.pivot.y;
  50268. this._vertex.z += this._copy.pivot.z;
  50269. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50270. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50271. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50272. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50273. }
  50274. particle.position.x = 0.0;
  50275. particle.position.y = 0.0;
  50276. particle.position.z = 0.0;
  50277. particle.rotation.x = 0.0;
  50278. particle.rotation.y = 0.0;
  50279. particle.rotation.z = 0.0;
  50280. particle.rotationQuaternion = null;
  50281. particle.scaling.x = 1.0;
  50282. particle.scaling.y = 1.0;
  50283. particle.scaling.z = 1.0;
  50284. };
  50285. /**
  50286. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50287. * @returns the SPS.
  50288. */
  50289. SolidParticleSystem.prototype.rebuildMesh = function () {
  50290. for (var p = 0; p < this.particles.length; p++) {
  50291. this._rebuildParticle(this.particles[p]);
  50292. }
  50293. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50294. return this;
  50295. };
  50296. /**
  50297. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50298. * This method calls `updateParticle()` for each particle of the SPS.
  50299. * For an animated SPS, it is usually called within the render loop.
  50300. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50301. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50302. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50303. * @returns the SPS.
  50304. */
  50305. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50306. if (start === void 0) { start = 0; }
  50307. if (end === void 0) { end = this.nbParticles - 1; }
  50308. if (update === void 0) { update = true; }
  50309. if (!this._updatable) {
  50310. return this;
  50311. }
  50312. // custom beforeUpdate
  50313. this.beforeUpdateParticles(start, end, update);
  50314. this._cam_axisX.x = 1.0;
  50315. this._cam_axisX.y = 0.0;
  50316. this._cam_axisX.z = 0.0;
  50317. this._cam_axisY.x = 0.0;
  50318. this._cam_axisY.y = 1.0;
  50319. this._cam_axisY.z = 0.0;
  50320. this._cam_axisZ.x = 0.0;
  50321. this._cam_axisZ.y = 0.0;
  50322. this._cam_axisZ.z = 1.0;
  50323. // cases when the World Matrix is to be computed first
  50324. if (this.billboard || this._depthSort) {
  50325. this.mesh.computeWorldMatrix(true);
  50326. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  50327. }
  50328. // if the particles will always face the camera
  50329. if (this.billboard) {
  50330. // compute the camera position and un-rotate it by the current mesh rotation
  50331. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  50332. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50333. this._cam_axisZ.normalize();
  50334. // same for camera up vector extracted from the cam view matrix
  50335. var view = this._camera.getViewMatrix(true);
  50336. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  50337. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50338. this._cam_axisY.normalize();
  50339. this._cam_axisX.normalize();
  50340. }
  50341. // if depthSort, compute the camera global position in the mesh local system
  50342. if (this._depthSort) {
  50343. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  50344. }
  50345. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50346. var idx = 0; // current position index in the global array positions32
  50347. var index = 0; // position start index in the global array positions32 of the current particle
  50348. var colidx = 0; // current color index in the global array colors32
  50349. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50350. var uvidx = 0; // current uv index in the global array uvs32
  50351. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50352. var pt = 0; // current index in the particle model shape
  50353. if (this.mesh.isFacetDataEnabled) {
  50354. this._computeBoundingBox = true;
  50355. }
  50356. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  50357. if (this._computeBoundingBox) {
  50358. if (start == 0 && end == this.nbParticles - 1) {
  50359. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50360. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50361. }
  50362. else {
  50363. if (this.mesh._boundingInfo) {
  50364. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  50365. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  50366. }
  50367. }
  50368. }
  50369. // particle loop
  50370. index = this.particles[start]._pos;
  50371. var vpos = (index / 3) | 0;
  50372. colorIndex = vpos * 4;
  50373. uvIndex = vpos * 2;
  50374. for (var p = start; p <= end; p++) {
  50375. this._particle = this.particles[p];
  50376. this._shape = this._particle._model._shape;
  50377. this._shapeUV = this._particle._model._shapeUV;
  50378. // call to custom user function to update the particle properties
  50379. this.updateParticle(this._particle);
  50380. // camera-particle distance for depth sorting
  50381. if (this._depthSort && this._depthSortParticles) {
  50382. var dsp = this.depthSortedParticles[p];
  50383. dsp.ind = this._particle._ind;
  50384. dsp.indicesLength = this._particle._model._indicesLength;
  50385. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  50386. }
  50387. // skip the computations for inactive or already invisible particles
  50388. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  50389. // increment indexes for the next particle
  50390. pt = this._shape.length;
  50391. index += pt * 3;
  50392. colorIndex += pt * 4;
  50393. uvIndex += pt * 2;
  50394. continue;
  50395. }
  50396. if (this._particle.isVisible) {
  50397. this._particle._stillInvisible = false; // un-mark permanent invisibility
  50398. // particle rotation matrix
  50399. if (this.billboard) {
  50400. this._particle.rotation.x = 0.0;
  50401. this._particle.rotation.y = 0.0;
  50402. }
  50403. if (this._computeParticleRotation || this.billboard) {
  50404. if (this._particle.rotationQuaternion) {
  50405. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50406. }
  50407. else {
  50408. this._yaw = this._particle.rotation.y;
  50409. this._pitch = this._particle.rotation.x;
  50410. this._roll = this._particle.rotation.z;
  50411. this._quaternionRotationYPR();
  50412. }
  50413. this._quaternionToRotationMatrix();
  50414. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  50415. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  50416. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  50417. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  50418. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  50419. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  50420. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  50421. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  50422. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  50423. }
  50424. // particle vertex loop
  50425. for (pt = 0; pt < this._shape.length; pt++) {
  50426. idx = index + pt * 3;
  50427. colidx = colorIndex + pt * 4;
  50428. uvidx = uvIndex + pt * 2;
  50429. this._vertex.x = this._shape[pt].x;
  50430. this._vertex.y = this._shape[pt].y;
  50431. this._vertex.z = this._shape[pt].z;
  50432. if (this._computeParticleVertex) {
  50433. this.updateParticleVertex(this._particle, this._vertex, pt);
  50434. }
  50435. // positions
  50436. this._vertex.x *= this._particle.scaling.x;
  50437. this._vertex.y *= this._particle.scaling.y;
  50438. this._vertex.z *= this._particle.scaling.z;
  50439. this._vertex.x += this._particle.pivot.x;
  50440. this._vertex.y += this._particle.pivot.y;
  50441. this._vertex.z += this._particle.pivot.z;
  50442. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50443. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50444. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50445. 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;
  50446. 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;
  50447. 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;
  50448. if (this._computeBoundingBox) {
  50449. if (this._positions32[idx] < this._minimum.x) {
  50450. this._minimum.x = this._positions32[idx];
  50451. }
  50452. if (this._positions32[idx] > this._maximum.x) {
  50453. this._maximum.x = this._positions32[idx];
  50454. }
  50455. if (this._positions32[idx + 1] < this._minimum.y) {
  50456. this._minimum.y = this._positions32[idx + 1];
  50457. }
  50458. if (this._positions32[idx + 1] > this._maximum.y) {
  50459. this._maximum.y = this._positions32[idx + 1];
  50460. }
  50461. if (this._positions32[idx + 2] < this._minimum.z) {
  50462. this._minimum.z = this._positions32[idx + 2];
  50463. }
  50464. if (this._positions32[idx + 2] > this._maximum.z) {
  50465. this._maximum.z = this._positions32[idx + 2];
  50466. }
  50467. }
  50468. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50469. if (!this._computeParticleVertex) {
  50470. this._normal.x = this._fixedNormal32[idx];
  50471. this._normal.y = this._fixedNormal32[idx + 1];
  50472. this._normal.z = this._fixedNormal32[idx + 2];
  50473. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  50474. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  50475. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  50476. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50477. 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;
  50478. 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;
  50479. }
  50480. if (this._computeParticleColor && this._particle.color) {
  50481. this._colors32[colidx] = this._particle.color.r;
  50482. this._colors32[colidx + 1] = this._particle.color.g;
  50483. this._colors32[colidx + 2] = this._particle.color.b;
  50484. this._colors32[colidx + 3] = this._particle.color.a;
  50485. }
  50486. if (this._computeParticleTexture) {
  50487. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50488. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50489. }
  50490. }
  50491. }
  50492. else {
  50493. this._particle._stillInvisible = true; // mark the particle as invisible
  50494. for (pt = 0; pt < this._shape.length; pt++) {
  50495. idx = index + pt * 3;
  50496. colidx = colorIndex + pt * 4;
  50497. uvidx = uvIndex + pt * 2;
  50498. this._positions32[idx] = 0.0;
  50499. this._positions32[idx + 1] = 0.0;
  50500. this._positions32[idx + 2] = 0.0;
  50501. this._normals32[idx] = 0.0;
  50502. this._normals32[idx + 1] = 0.0;
  50503. this._normals32[idx + 2] = 0.0;
  50504. if (this._computeParticleColor && this._particle.color) {
  50505. this._colors32[colidx] = this._particle.color.r;
  50506. this._colors32[colidx + 1] = this._particle.color.g;
  50507. this._colors32[colidx + 2] = this._particle.color.b;
  50508. this._colors32[colidx + 3] = this._particle.color.a;
  50509. }
  50510. if (this._computeParticleTexture) {
  50511. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50512. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50513. }
  50514. }
  50515. }
  50516. // if the particle intersections must be computed : update the bbInfo
  50517. if (this._particlesIntersect) {
  50518. var bInfo = this._particle._boundingInfo;
  50519. var bBox = bInfo.boundingBox;
  50520. var bSphere = bInfo.boundingSphere;
  50521. if (!this._bSphereOnly) {
  50522. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50523. for (var b = 0; b < bBox.vectors.length; b++) {
  50524. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50525. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50526. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50527. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50528. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50529. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50530. 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;
  50531. 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;
  50532. 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;
  50533. }
  50534. bBox._update(this.mesh._worldMatrix);
  50535. }
  50536. // place and scale the particle bouding sphere in the SPS local system, then update it
  50537. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50538. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50539. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50540. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50541. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50542. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50543. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50544. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50545. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50546. 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));
  50547. bSphere._update(this.mesh._worldMatrix);
  50548. }
  50549. // increment indexes for the next particle
  50550. index = idx + 3;
  50551. colorIndex = colidx + 4;
  50552. uvIndex = uvidx + 2;
  50553. }
  50554. // if the VBO must be updated
  50555. if (update) {
  50556. if (this._computeParticleColor) {
  50557. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50558. }
  50559. if (this._computeParticleTexture) {
  50560. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50561. }
  50562. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50563. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50564. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50565. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50566. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50567. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50568. for (var i = 0; i < this._normals32.length; i++) {
  50569. this._fixedNormal32[i] = this._normals32[i];
  50570. }
  50571. }
  50572. if (!this.mesh.areNormalsFrozen) {
  50573. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50574. }
  50575. }
  50576. if (this._depthSort && this._depthSortParticles) {
  50577. this.depthSortedParticles.sort(this._depthSortFunction);
  50578. var dspl = this.depthSortedParticles.length;
  50579. var sorted = 0;
  50580. var lind = 0;
  50581. var sind = 0;
  50582. var sid = 0;
  50583. for (sorted = 0; sorted < dspl; sorted++) {
  50584. lind = this.depthSortedParticles[sorted].indicesLength;
  50585. sind = this.depthSortedParticles[sorted].ind;
  50586. for (var i = 0; i < lind; i++) {
  50587. this._indices32[sid] = this._indices[sind + i];
  50588. sid++;
  50589. }
  50590. }
  50591. this.mesh.updateIndices(this._indices32);
  50592. }
  50593. }
  50594. if (this._computeBoundingBox) {
  50595. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50596. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50597. }
  50598. this.afterUpdateParticles(start, end, update);
  50599. return this;
  50600. };
  50601. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50602. this._halfroll = this._roll * 0.5;
  50603. this._halfpitch = this._pitch * 0.5;
  50604. this._halfyaw = this._yaw * 0.5;
  50605. this._sinRoll = Math.sin(this._halfroll);
  50606. this._cosRoll = Math.cos(this._halfroll);
  50607. this._sinPitch = Math.sin(this._halfpitch);
  50608. this._cosPitch = Math.cos(this._halfpitch);
  50609. this._sinYaw = Math.sin(this._halfyaw);
  50610. this._cosYaw = Math.cos(this._halfyaw);
  50611. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50612. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50613. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50614. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50615. };
  50616. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50617. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50618. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50619. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50620. this._rotMatrix.m[3] = 0;
  50621. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50622. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50623. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50624. this._rotMatrix.m[7] = 0;
  50625. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50626. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50627. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50628. this._rotMatrix.m[11] = 0;
  50629. this._rotMatrix.m[12] = 0;
  50630. this._rotMatrix.m[13] = 0;
  50631. this._rotMatrix.m[14] = 0;
  50632. this._rotMatrix.m[15] = 1.0;
  50633. };
  50634. /**
  50635. * Disposes the SPS.
  50636. */
  50637. SolidParticleSystem.prototype.dispose = function () {
  50638. this.mesh.dispose();
  50639. this.vars = null;
  50640. // drop references to internal big arrays for the GC
  50641. this._positions = null;
  50642. this._indices = null;
  50643. this._normals = null;
  50644. this._uvs = null;
  50645. this._colors = null;
  50646. this._indices32 = null;
  50647. this._positions32 = null;
  50648. this._normals32 = null;
  50649. this._fixedNormal32 = null;
  50650. this._uvs32 = null;
  50651. this._colors32 = null;
  50652. this.pickedParticles = null;
  50653. };
  50654. /**
  50655. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50656. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50657. * @returns the SPS.
  50658. */
  50659. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50660. if (!this._isVisibilityBoxLocked) {
  50661. this.mesh.refreshBoundingInfo();
  50662. }
  50663. return this;
  50664. };
  50665. /**
  50666. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50667. * @param size the size (float) of the visibility box
  50668. * note : this doesn't lock the SPS mesh bounding box.
  50669. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50670. */
  50671. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50672. var vis = size / 2;
  50673. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50674. };
  50675. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50676. /**
  50677. * Gets whether the SPS as always visible or not
  50678. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50679. */
  50680. get: function () {
  50681. return this._alwaysVisible;
  50682. },
  50683. /**
  50684. * Sets the SPS as always visible or not
  50685. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50686. */
  50687. set: function (val) {
  50688. this._alwaysVisible = val;
  50689. this.mesh.alwaysSelectAsActiveMesh = val;
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50695. /**
  50696. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50697. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50698. */
  50699. get: function () {
  50700. return this._isVisibilityBoxLocked;
  50701. },
  50702. /**
  50703. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50704. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50705. */
  50706. set: function (val) {
  50707. this._isVisibilityBoxLocked = val;
  50708. var boundingInfo = this.mesh.getBoundingInfo();
  50709. boundingInfo.isLocked = val;
  50710. },
  50711. enumerable: true,
  50712. configurable: true
  50713. });
  50714. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50715. /**
  50716. * Gets if `setParticles()` computes the particle rotations or not.
  50717. * Default value : true. The SPS is faster when it's set to false.
  50718. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50719. */
  50720. get: function () {
  50721. return this._computeParticleRotation;
  50722. },
  50723. /**
  50724. * Tells to `setParticles()` to compute the particle rotations or not.
  50725. * Default value : true. The SPS is faster when it's set to false.
  50726. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50727. */
  50728. set: function (val) {
  50729. this._computeParticleRotation = val;
  50730. },
  50731. enumerable: true,
  50732. configurable: true
  50733. });
  50734. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50735. /**
  50736. * Gets if `setParticles()` computes the particle colors or not.
  50737. * Default value : true. The SPS is faster when it's set to false.
  50738. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50739. */
  50740. get: function () {
  50741. return this._computeParticleColor;
  50742. },
  50743. /**
  50744. * Tells to `setParticles()` to compute the particle colors or not.
  50745. * Default value : true. The SPS is faster when it's set to false.
  50746. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50747. */
  50748. set: function (val) {
  50749. this._computeParticleColor = val;
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50755. /**
  50756. * Gets if `setParticles()` computes the particle textures or not.
  50757. * Default value : true. The SPS is faster when it's set to false.
  50758. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50759. */
  50760. get: function () {
  50761. return this._computeParticleTexture;
  50762. },
  50763. set: function (val) {
  50764. this._computeParticleTexture = val;
  50765. },
  50766. enumerable: true,
  50767. configurable: true
  50768. });
  50769. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50770. /**
  50771. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50772. * Default value : false. The SPS is faster when it's set to false.
  50773. * Note : the particle custom vertex positions aren't stored values.
  50774. */
  50775. get: function () {
  50776. return this._computeParticleVertex;
  50777. },
  50778. /**
  50779. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50780. * Default value : false. The SPS is faster when it's set to false.
  50781. * Note : the particle custom vertex positions aren't stored values.
  50782. */
  50783. set: function (val) {
  50784. this._computeParticleVertex = val;
  50785. },
  50786. enumerable: true,
  50787. configurable: true
  50788. });
  50789. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50790. /**
  50791. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50792. */
  50793. get: function () {
  50794. return this._computeBoundingBox;
  50795. },
  50796. /**
  50797. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50798. */
  50799. set: function (val) {
  50800. this._computeBoundingBox = val;
  50801. },
  50802. enumerable: true,
  50803. configurable: true
  50804. });
  50805. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50806. /**
  50807. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50808. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50809. * Default : `true`
  50810. */
  50811. get: function () {
  50812. return this._depthSortParticles;
  50813. },
  50814. /**
  50815. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50816. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50817. * Default : `true`
  50818. */
  50819. set: function (val) {
  50820. this._depthSortParticles = val;
  50821. },
  50822. enumerable: true,
  50823. configurable: true
  50824. });
  50825. // =======================================================================
  50826. // Particle behavior logic
  50827. // these following methods may be overwritten by the user to fit his needs
  50828. /**
  50829. * This function does nothing. It may be overwritten to set all the particle first values.
  50830. * The SPS doesn't call this function, you may have to call it by your own.
  50831. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50832. */
  50833. SolidParticleSystem.prototype.initParticles = function () {
  50834. };
  50835. /**
  50836. * This function does nothing. It may be overwritten to recycle a particle.
  50837. * The SPS doesn't call this function, you may have to call it by your own.
  50838. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50839. * @param particle The particle to recycle
  50840. * @returns the recycled particle
  50841. */
  50842. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50843. return particle;
  50844. };
  50845. /**
  50846. * Updates a particle : this function should be overwritten by the user.
  50847. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50848. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50849. * @example : just set a particle position or velocity and recycle conditions
  50850. * @param particle The particle to update
  50851. * @returns the updated particle
  50852. */
  50853. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50854. return particle;
  50855. };
  50856. /**
  50857. * Updates a vertex of a particle : it can be overwritten by the user.
  50858. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50859. * @param particle the current particle
  50860. * @param vertex the current index of the current particle
  50861. * @param pt the index of the current vertex in the particle shape
  50862. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50863. * @example : just set a vertex particle position
  50864. * @returns the updated vertex
  50865. */
  50866. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50867. return vertex;
  50868. };
  50869. /**
  50870. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50871. * This does nothing and may be overwritten by the user.
  50872. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50873. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50874. * @param update the boolean update value actually passed to setParticles()
  50875. */
  50876. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50877. };
  50878. /**
  50879. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50880. * This will be passed three parameters.
  50881. * This does nothing and may be overwritten by the user.
  50882. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50883. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50884. * @param update the boolean update value actually passed to setParticles()
  50885. */
  50886. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50887. };
  50888. return SolidParticleSystem;
  50889. }());
  50890. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50891. })(BABYLON || (BABYLON = {}));
  50892. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50893. var BABYLON;
  50894. (function (BABYLON) {
  50895. var ShaderMaterial = /** @class */ (function (_super) {
  50896. __extends(ShaderMaterial, _super);
  50897. function ShaderMaterial(name, scene, shaderPath, options) {
  50898. var _this = _super.call(this, name, scene) || this;
  50899. _this._textures = {};
  50900. _this._textureArrays = {};
  50901. _this._floats = {};
  50902. _this._ints = {};
  50903. _this._floatsArrays = {};
  50904. _this._colors3 = {};
  50905. _this._colors3Arrays = {};
  50906. _this._colors4 = {};
  50907. _this._vectors2 = {};
  50908. _this._vectors3 = {};
  50909. _this._vectors4 = {};
  50910. _this._matrices = {};
  50911. _this._matrices3x3 = {};
  50912. _this._matrices2x2 = {};
  50913. _this._vectors2Arrays = {};
  50914. _this._vectors3Arrays = {};
  50915. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50916. _this._shaderPath = shaderPath;
  50917. options.needAlphaBlending = options.needAlphaBlending || false;
  50918. options.needAlphaTesting = options.needAlphaTesting || false;
  50919. options.attributes = options.attributes || ["position", "normal", "uv"];
  50920. options.uniforms = options.uniforms || ["worldViewProjection"];
  50921. options.uniformBuffers = options.uniformBuffers || [];
  50922. options.samplers = options.samplers || [];
  50923. options.defines = options.defines || [];
  50924. _this._options = options;
  50925. return _this;
  50926. }
  50927. ShaderMaterial.prototype.getClassName = function () {
  50928. return "ShaderMaterial";
  50929. };
  50930. ShaderMaterial.prototype.needAlphaBlending = function () {
  50931. return this._options.needAlphaBlending;
  50932. };
  50933. ShaderMaterial.prototype.needAlphaTesting = function () {
  50934. return this._options.needAlphaTesting;
  50935. };
  50936. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50937. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50938. this._options.uniforms.push(uniformName);
  50939. }
  50940. };
  50941. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50942. if (this._options.samplers.indexOf(name) === -1) {
  50943. this._options.samplers.push(name);
  50944. }
  50945. this._textures[name] = texture;
  50946. return this;
  50947. };
  50948. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50949. if (this._options.samplers.indexOf(name) === -1) {
  50950. this._options.samplers.push(name);
  50951. }
  50952. this._checkUniform(name);
  50953. this._textureArrays[name] = textures;
  50954. return this;
  50955. };
  50956. ShaderMaterial.prototype.setFloat = function (name, value) {
  50957. this._checkUniform(name);
  50958. this._floats[name] = value;
  50959. return this;
  50960. };
  50961. ShaderMaterial.prototype.setInt = function (name, value) {
  50962. this._checkUniform(name);
  50963. this._ints[name] = value;
  50964. return this;
  50965. };
  50966. ShaderMaterial.prototype.setFloats = function (name, value) {
  50967. this._checkUniform(name);
  50968. this._floatsArrays[name] = value;
  50969. return this;
  50970. };
  50971. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50972. this._checkUniform(name);
  50973. this._colors3[name] = value;
  50974. return this;
  50975. };
  50976. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50977. this._checkUniform(name);
  50978. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50979. color.toArray(arr, arr.length);
  50980. return arr;
  50981. }, []);
  50982. return this;
  50983. };
  50984. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50985. this._checkUniform(name);
  50986. this._colors4[name] = value;
  50987. return this;
  50988. };
  50989. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50990. this._checkUniform(name);
  50991. this._vectors2[name] = value;
  50992. return this;
  50993. };
  50994. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50995. this._checkUniform(name);
  50996. this._vectors3[name] = value;
  50997. return this;
  50998. };
  50999. ShaderMaterial.prototype.setVector4 = function (name, value) {
  51000. this._checkUniform(name);
  51001. this._vectors4[name] = value;
  51002. return this;
  51003. };
  51004. ShaderMaterial.prototype.setMatrix = function (name, value) {
  51005. this._checkUniform(name);
  51006. this._matrices[name] = value;
  51007. return this;
  51008. };
  51009. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  51010. this._checkUniform(name);
  51011. this._matrices3x3[name] = value;
  51012. return this;
  51013. };
  51014. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  51015. this._checkUniform(name);
  51016. this._matrices2x2[name] = value;
  51017. return this;
  51018. };
  51019. ShaderMaterial.prototype.setArray2 = function (name, value) {
  51020. this._checkUniform(name);
  51021. this._vectors2Arrays[name] = value;
  51022. return this;
  51023. };
  51024. ShaderMaterial.prototype.setArray3 = function (name, value) {
  51025. this._checkUniform(name);
  51026. this._vectors3Arrays[name] = value;
  51027. return this;
  51028. };
  51029. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51030. if (!mesh) {
  51031. return true;
  51032. }
  51033. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  51034. return false;
  51035. }
  51036. return false;
  51037. };
  51038. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  51039. var scene = this.getScene();
  51040. var engine = scene.getEngine();
  51041. if (!this.checkReadyOnEveryCall) {
  51042. if (this._renderId === scene.getRenderId()) {
  51043. if (this._checkCache(scene, mesh, useInstances)) {
  51044. return true;
  51045. }
  51046. }
  51047. }
  51048. // Instances
  51049. var defines = [];
  51050. var attribs = [];
  51051. var fallbacks = new BABYLON.EffectFallbacks();
  51052. if (useInstances) {
  51053. defines.push("#define INSTANCES");
  51054. }
  51055. for (var index = 0; index < this._options.defines.length; index++) {
  51056. defines.push(this._options.defines[index]);
  51057. }
  51058. for (var index = 0; index < this._options.attributes.length; index++) {
  51059. attribs.push(this._options.attributes[index]);
  51060. }
  51061. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  51062. attribs.push(BABYLON.VertexBuffer.ColorKind);
  51063. defines.push("#define VERTEXCOLOR");
  51064. }
  51065. // Bones
  51066. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  51067. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51068. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51069. if (mesh.numBoneInfluencers > 4) {
  51070. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51071. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51072. }
  51073. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51074. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51075. fallbacks.addCPUSkinningFallback(0, mesh);
  51076. if (this._options.uniforms.indexOf("mBones") === -1) {
  51077. this._options.uniforms.push("mBones");
  51078. }
  51079. }
  51080. else {
  51081. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51082. }
  51083. // Textures
  51084. for (var name in this._textures) {
  51085. if (!this._textures[name].isReady()) {
  51086. return false;
  51087. }
  51088. }
  51089. // Alpha test
  51090. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  51091. defines.push("#define ALPHATEST");
  51092. }
  51093. var previousEffect = this._effect;
  51094. var join = defines.join("\n");
  51095. this._effect = engine.createEffect(this._shaderPath, {
  51096. attributes: attribs,
  51097. uniformsNames: this._options.uniforms,
  51098. uniformBuffersNames: this._options.uniformBuffers,
  51099. samplers: this._options.samplers,
  51100. defines: join,
  51101. fallbacks: fallbacks,
  51102. onCompiled: this.onCompiled,
  51103. onError: this.onError
  51104. }, engine);
  51105. if (!this._effect.isReady()) {
  51106. return false;
  51107. }
  51108. if (previousEffect !== this._effect) {
  51109. scene.resetCachedMaterial();
  51110. }
  51111. this._renderId = scene.getRenderId();
  51112. return true;
  51113. };
  51114. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  51115. var scene = this.getScene();
  51116. if (!this._effect) {
  51117. return;
  51118. }
  51119. if (this._options.uniforms.indexOf("world") !== -1) {
  51120. this._effect.setMatrix("world", world);
  51121. }
  51122. if (this._options.uniforms.indexOf("worldView") !== -1) {
  51123. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  51124. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  51125. }
  51126. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  51127. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  51128. }
  51129. };
  51130. ShaderMaterial.prototype.bind = function (world, mesh) {
  51131. // Std values
  51132. this.bindOnlyWorldMatrix(world);
  51133. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  51134. if (this._options.uniforms.indexOf("view") !== -1) {
  51135. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  51136. }
  51137. if (this._options.uniforms.indexOf("projection") !== -1) {
  51138. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  51139. }
  51140. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  51141. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  51142. }
  51143. // Bones
  51144. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  51145. var name;
  51146. // Texture
  51147. for (name in this._textures) {
  51148. this._effect.setTexture(name, this._textures[name]);
  51149. }
  51150. // Texture arrays
  51151. for (name in this._textureArrays) {
  51152. this._effect.setTextureArray(name, this._textureArrays[name]);
  51153. }
  51154. // Int
  51155. for (name in this._ints) {
  51156. this._effect.setInt(name, this._ints[name]);
  51157. }
  51158. // Float
  51159. for (name in this._floats) {
  51160. this._effect.setFloat(name, this._floats[name]);
  51161. }
  51162. // Floats
  51163. for (name in this._floatsArrays) {
  51164. this._effect.setArray(name, this._floatsArrays[name]);
  51165. }
  51166. // Color3
  51167. for (name in this._colors3) {
  51168. this._effect.setColor3(name, this._colors3[name]);
  51169. }
  51170. for (name in this._colors3Arrays) {
  51171. this._effect.setArray3(name, this._colors3Arrays[name]);
  51172. }
  51173. // Color4
  51174. for (name in this._colors4) {
  51175. var color = this._colors4[name];
  51176. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  51177. }
  51178. // Vector2
  51179. for (name in this._vectors2) {
  51180. this._effect.setVector2(name, this._vectors2[name]);
  51181. }
  51182. // Vector3
  51183. for (name in this._vectors3) {
  51184. this._effect.setVector3(name, this._vectors3[name]);
  51185. }
  51186. // Vector4
  51187. for (name in this._vectors4) {
  51188. this._effect.setVector4(name, this._vectors4[name]);
  51189. }
  51190. // Matrix
  51191. for (name in this._matrices) {
  51192. this._effect.setMatrix(name, this._matrices[name]);
  51193. }
  51194. // Matrix 3x3
  51195. for (name in this._matrices3x3) {
  51196. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  51197. }
  51198. // Matrix 2x2
  51199. for (name in this._matrices2x2) {
  51200. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  51201. }
  51202. // Vector2Array
  51203. for (name in this._vectors2Arrays) {
  51204. this._effect.setArray2(name, this._vectors2Arrays[name]);
  51205. }
  51206. // Vector3Array
  51207. for (name in this._vectors3Arrays) {
  51208. this._effect.setArray3(name, this._vectors3Arrays[name]);
  51209. }
  51210. }
  51211. this._afterBind(mesh);
  51212. };
  51213. ShaderMaterial.prototype.getActiveTextures = function () {
  51214. var activeTextures = _super.prototype.getActiveTextures.call(this);
  51215. for (var name in this._textures) {
  51216. activeTextures.push(this._textures[name]);
  51217. }
  51218. for (var name in this._textureArrays) {
  51219. var array = this._textureArrays[name];
  51220. for (var index = 0; index < array.length; index++) {
  51221. activeTextures.push(array[index]);
  51222. }
  51223. }
  51224. return activeTextures;
  51225. };
  51226. ShaderMaterial.prototype.hasTexture = function (texture) {
  51227. if (_super.prototype.hasTexture.call(this, texture)) {
  51228. return true;
  51229. }
  51230. for (var name in this._textures) {
  51231. if (this._textures[name] === texture) {
  51232. return true;
  51233. }
  51234. }
  51235. for (var name in this._textureArrays) {
  51236. var array = this._textureArrays[name];
  51237. for (var index = 0; index < array.length; index++) {
  51238. if (array[index] === texture) {
  51239. return true;
  51240. }
  51241. }
  51242. }
  51243. return false;
  51244. };
  51245. ShaderMaterial.prototype.clone = function (name) {
  51246. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  51247. return newShaderMaterial;
  51248. };
  51249. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51250. if (forceDisposeTextures) {
  51251. var name;
  51252. for (name in this._textures) {
  51253. this._textures[name].dispose();
  51254. }
  51255. for (name in this._textureArrays) {
  51256. var array = this._textureArrays[name];
  51257. for (var index = 0; index < array.length; index++) {
  51258. array[index].dispose();
  51259. }
  51260. }
  51261. }
  51262. this._textures = {};
  51263. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51264. };
  51265. ShaderMaterial.prototype.serialize = function () {
  51266. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51267. serializationObject.customType = "BABYLON.ShaderMaterial";
  51268. serializationObject.options = this._options;
  51269. serializationObject.shaderPath = this._shaderPath;
  51270. var name;
  51271. // Texture
  51272. serializationObject.textures = {};
  51273. for (name in this._textures) {
  51274. serializationObject.textures[name] = this._textures[name].serialize();
  51275. }
  51276. // Texture arrays
  51277. serializationObject.textureArrays = {};
  51278. for (name in this._textureArrays) {
  51279. serializationObject.textureArrays[name] = [];
  51280. var array = this._textureArrays[name];
  51281. for (var index = 0; index < array.length; index++) {
  51282. serializationObject.textureArrays[name].push(array[index].serialize());
  51283. }
  51284. }
  51285. // Float
  51286. serializationObject.floats = {};
  51287. for (name in this._floats) {
  51288. serializationObject.floats[name] = this._floats[name];
  51289. }
  51290. // Float s
  51291. serializationObject.FloatArrays = {};
  51292. for (name in this._floatsArrays) {
  51293. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  51294. }
  51295. // Color3
  51296. serializationObject.colors3 = {};
  51297. for (name in this._colors3) {
  51298. serializationObject.colors3[name] = this._colors3[name].asArray();
  51299. }
  51300. // Color3 array
  51301. serializationObject.colors3Arrays = {};
  51302. for (name in this._colors3Arrays) {
  51303. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  51304. }
  51305. // Color4
  51306. serializationObject.colors4 = {};
  51307. for (name in this._colors4) {
  51308. serializationObject.colors4[name] = this._colors4[name].asArray();
  51309. }
  51310. // Vector2
  51311. serializationObject.vectors2 = {};
  51312. for (name in this._vectors2) {
  51313. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  51314. }
  51315. // Vector3
  51316. serializationObject.vectors3 = {};
  51317. for (name in this._vectors3) {
  51318. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  51319. }
  51320. // Vector4
  51321. serializationObject.vectors4 = {};
  51322. for (name in this._vectors4) {
  51323. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  51324. }
  51325. // Matrix
  51326. serializationObject.matrices = {};
  51327. for (name in this._matrices) {
  51328. serializationObject.matrices[name] = this._matrices[name].asArray();
  51329. }
  51330. // Matrix 3x3
  51331. serializationObject.matrices3x3 = {};
  51332. for (name in this._matrices3x3) {
  51333. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  51334. }
  51335. // Matrix 2x2
  51336. serializationObject.matrices2x2 = {};
  51337. for (name in this._matrices2x2) {
  51338. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  51339. }
  51340. // Vector2Array
  51341. serializationObject.vectors2Arrays = {};
  51342. for (name in this._vectors2Arrays) {
  51343. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  51344. }
  51345. // Vector3Array
  51346. serializationObject.vectors3Arrays = {};
  51347. for (name in this._vectors3Arrays) {
  51348. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  51349. }
  51350. return serializationObject;
  51351. };
  51352. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  51353. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  51354. var name;
  51355. // Texture
  51356. for (name in source.textures) {
  51357. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  51358. }
  51359. // Texture arrays
  51360. for (name in source.textureArrays) {
  51361. var array = source.textureArrays[name];
  51362. var textureArray = new Array();
  51363. for (var index = 0; index < array.length; index++) {
  51364. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  51365. }
  51366. material.setTextureArray(name, textureArray);
  51367. }
  51368. // Float
  51369. for (name in source.floats) {
  51370. material.setFloat(name, source.floats[name]);
  51371. }
  51372. // Float s
  51373. for (name in source.floatsArrays) {
  51374. material.setFloats(name, source.floatsArrays[name]);
  51375. }
  51376. // Color3
  51377. for (name in source.colors3) {
  51378. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  51379. }
  51380. // Color3 arrays
  51381. for (name in source.colors3Arrays) {
  51382. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  51383. if (i % 3 === 0) {
  51384. arr.push([num]);
  51385. }
  51386. else {
  51387. arr[arr.length - 1].push(num);
  51388. }
  51389. return arr;
  51390. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  51391. material.setColor3Array(name, colors);
  51392. }
  51393. // Color4
  51394. for (name in source.colors4) {
  51395. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  51396. }
  51397. // Vector2
  51398. for (name in source.vectors2) {
  51399. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  51400. }
  51401. // Vector3
  51402. for (name in source.vectors3) {
  51403. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  51404. }
  51405. // Vector4
  51406. for (name in source.vectors4) {
  51407. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  51408. }
  51409. // Matrix
  51410. for (name in source.matrices) {
  51411. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  51412. }
  51413. // Matrix 3x3
  51414. for (name in source.matrices3x3) {
  51415. material.setMatrix3x3(name, source.matrices3x3[name]);
  51416. }
  51417. // Matrix 2x2
  51418. for (name in source.matrices2x2) {
  51419. material.setMatrix2x2(name, source.matrices2x2[name]);
  51420. }
  51421. // Vector2Array
  51422. for (name in source.vectors2Arrays) {
  51423. material.setArray2(name, source.vectors2Arrays[name]);
  51424. }
  51425. // Vector3Array
  51426. for (name in source.vectors3Arrays) {
  51427. material.setArray3(name, source.vectors3Arrays[name]);
  51428. }
  51429. return material;
  51430. };
  51431. return ShaderMaterial;
  51432. }(BABYLON.Material));
  51433. BABYLON.ShaderMaterial = ShaderMaterial;
  51434. })(BABYLON || (BABYLON = {}));
  51435. //# sourceMappingURL=babylon.shaderMaterial.js.map
  51436. var BABYLON;
  51437. (function (BABYLON) {
  51438. var GroundMesh = /** @class */ (function (_super) {
  51439. __extends(GroundMesh, _super);
  51440. function GroundMesh(name, scene) {
  51441. var _this = _super.call(this, name, scene) || this;
  51442. _this.generateOctree = false;
  51443. return _this;
  51444. }
  51445. GroundMesh.prototype.getClassName = function () {
  51446. return "GroundMesh";
  51447. };
  51448. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  51449. get: function () {
  51450. return Math.min(this._subdivisionsX, this._subdivisionsY);
  51451. },
  51452. enumerable: true,
  51453. configurable: true
  51454. });
  51455. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  51456. get: function () {
  51457. return this._subdivisionsX;
  51458. },
  51459. enumerable: true,
  51460. configurable: true
  51461. });
  51462. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  51463. get: function () {
  51464. return this._subdivisionsY;
  51465. },
  51466. enumerable: true,
  51467. configurable: true
  51468. });
  51469. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  51470. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  51471. this._subdivisionsX = chunksCount;
  51472. this._subdivisionsY = chunksCount;
  51473. this.subdivide(chunksCount);
  51474. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  51475. };
  51476. /**
  51477. * Returns a height (y) value in the Worl system :
  51478. * the ground altitude at the coordinates (x, z) expressed in the World system.
  51479. * Returns the ground y position if (x, z) are outside the ground surface.
  51480. */
  51481. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  51482. var world = this.getWorldMatrix();
  51483. var invMat = BABYLON.Tmp.Matrix[5];
  51484. world.invertToRef(invMat);
  51485. var tmpVect = BABYLON.Tmp.Vector3[8];
  51486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  51487. x = tmpVect.x;
  51488. z = tmpVect.z;
  51489. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51490. return this.position.y;
  51491. }
  51492. if (!this._heightQuads || this._heightQuads.length == 0) {
  51493. this._initHeightQuads();
  51494. this._computeHeightQuads();
  51495. }
  51496. var facet = this._getFacetAt(x, z);
  51497. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  51498. // return y in the World system
  51499. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  51500. return tmpVect.y;
  51501. };
  51502. /**
  51503. * Returns a normalized vector (Vector3) orthogonal to the ground
  51504. * at the ground coordinates (x, z) expressed in the World system.
  51505. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  51506. */
  51507. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  51508. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  51509. this.getNormalAtCoordinatesToRef(x, z, normal);
  51510. return normal;
  51511. };
  51512. /**
  51513. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  51514. * at the ground coordinates (x, z) expressed in the World system.
  51515. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  51516. * Returns the GroundMesh.
  51517. */
  51518. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  51519. var world = this.getWorldMatrix();
  51520. var tmpMat = BABYLON.Tmp.Matrix[5];
  51521. world.invertToRef(tmpMat);
  51522. var tmpVect = BABYLON.Tmp.Vector3[8];
  51523. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  51524. x = tmpVect.x;
  51525. z = tmpVect.z;
  51526. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51527. return this;
  51528. }
  51529. if (!this._heightQuads || this._heightQuads.length == 0) {
  51530. this._initHeightQuads();
  51531. this._computeHeightQuads();
  51532. }
  51533. var facet = this._getFacetAt(x, z);
  51534. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51535. return this;
  51536. };
  51537. /**
  51538. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51539. * if the ground has been updated.
  51540. * This can be used in the render loop.
  51541. * Returns the GroundMesh.
  51542. */
  51543. GroundMesh.prototype.updateCoordinateHeights = function () {
  51544. if (!this._heightQuads || this._heightQuads.length == 0) {
  51545. this._initHeightQuads();
  51546. }
  51547. this._computeHeightQuads();
  51548. return this;
  51549. };
  51550. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51551. GroundMesh.prototype._getFacetAt = function (x, z) {
  51552. // retrieve col and row from x, z coordinates in the ground local system
  51553. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51554. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51555. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51556. var facet;
  51557. if (z < quad.slope.x * x + quad.slope.y) {
  51558. facet = quad.facet1;
  51559. }
  51560. else {
  51561. facet = quad.facet2;
  51562. }
  51563. return facet;
  51564. };
  51565. // Creates and populates the heightMap array with "facet" elements :
  51566. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51567. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51568. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51569. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51570. // Returns the GroundMesh.
  51571. GroundMesh.prototype._initHeightQuads = function () {
  51572. var subdivisionsX = this._subdivisionsX;
  51573. var subdivisionsY = this._subdivisionsY;
  51574. this._heightQuads = new Array();
  51575. for (var row = 0; row < subdivisionsY; row++) {
  51576. for (var col = 0; col < subdivisionsX; col++) {
  51577. 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) };
  51578. this._heightQuads[row * subdivisionsX + col] = quad;
  51579. }
  51580. }
  51581. return this;
  51582. };
  51583. // Compute each quad element values and update the the heightMap array :
  51584. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51585. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51586. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51587. // Returns the GroundMesh.
  51588. GroundMesh.prototype._computeHeightQuads = function () {
  51589. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51590. if (!positions) {
  51591. return this;
  51592. }
  51593. var v1 = BABYLON.Tmp.Vector3[3];
  51594. var v2 = BABYLON.Tmp.Vector3[2];
  51595. var v3 = BABYLON.Tmp.Vector3[1];
  51596. var v4 = BABYLON.Tmp.Vector3[0];
  51597. var v1v2 = BABYLON.Tmp.Vector3[4];
  51598. var v1v3 = BABYLON.Tmp.Vector3[5];
  51599. var v1v4 = BABYLON.Tmp.Vector3[6];
  51600. var norm1 = BABYLON.Tmp.Vector3[7];
  51601. var norm2 = BABYLON.Tmp.Vector3[8];
  51602. var i = 0;
  51603. var j = 0;
  51604. var k = 0;
  51605. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51606. var h = 0;
  51607. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51608. var d2 = 0;
  51609. var subdivisionsX = this._subdivisionsX;
  51610. var subdivisionsY = this._subdivisionsY;
  51611. for (var row = 0; row < subdivisionsY; row++) {
  51612. for (var col = 0; col < subdivisionsX; col++) {
  51613. i = col * 3;
  51614. j = row * (subdivisionsX + 1) * 3;
  51615. k = (row + 1) * (subdivisionsX + 1) * 3;
  51616. v1.x = positions[j + i];
  51617. v1.y = positions[j + i + 1];
  51618. v1.z = positions[j + i + 2];
  51619. v2.x = positions[j + i + 3];
  51620. v2.y = positions[j + i + 4];
  51621. v2.z = positions[j + i + 5];
  51622. v3.x = positions[k + i];
  51623. v3.y = positions[k + i + 1];
  51624. v3.z = positions[k + i + 2];
  51625. v4.x = positions[k + i + 3];
  51626. v4.y = positions[k + i + 4];
  51627. v4.z = positions[k + i + 5];
  51628. // 2D slope V1V4
  51629. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51630. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51631. // facet equations :
  51632. // we compute each facet normal vector
  51633. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51634. // we compute the value d by applying the equation to v1 which belongs to the plane
  51635. // then we store the facet equation in a Vector4
  51636. v2.subtractToRef(v1, v1v2);
  51637. v3.subtractToRef(v1, v1v3);
  51638. v4.subtractToRef(v1, v1v4);
  51639. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51640. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51641. norm1.normalize();
  51642. norm2.normalize();
  51643. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51644. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51645. var quad = this._heightQuads[row * subdivisionsX + col];
  51646. quad.slope.copyFromFloats(cd, h);
  51647. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51648. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51649. }
  51650. }
  51651. return this;
  51652. };
  51653. GroundMesh.prototype.serialize = function (serializationObject) {
  51654. _super.prototype.serialize.call(this, serializationObject);
  51655. serializationObject.subdivisionsX = this._subdivisionsX;
  51656. serializationObject.subdivisionsY = this._subdivisionsY;
  51657. serializationObject.minX = this._minX;
  51658. serializationObject.maxX = this._maxX;
  51659. serializationObject.minZ = this._minZ;
  51660. serializationObject.maxZ = this._maxZ;
  51661. serializationObject.width = this._width;
  51662. serializationObject.height = this._height;
  51663. };
  51664. GroundMesh.Parse = function (parsedMesh, scene) {
  51665. var result = new GroundMesh(parsedMesh.name, scene);
  51666. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51667. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51668. result._minX = parsedMesh.minX;
  51669. result._maxX = parsedMesh.maxX;
  51670. result._minZ = parsedMesh.minZ;
  51671. result._maxZ = parsedMesh.maxZ;
  51672. result._width = parsedMesh.width;
  51673. result._height = parsedMesh.height;
  51674. return result;
  51675. };
  51676. return GroundMesh;
  51677. }(BABYLON.Mesh));
  51678. BABYLON.GroundMesh = GroundMesh;
  51679. })(BABYLON || (BABYLON = {}));
  51680. //# sourceMappingURL=babylon.groundMesh.js.map
  51681. var BABYLON;
  51682. (function (BABYLON) {
  51683. /**
  51684. * Creates an instance based on a source mesh.
  51685. */
  51686. var InstancedMesh = /** @class */ (function (_super) {
  51687. __extends(InstancedMesh, _super);
  51688. function InstancedMesh(name, source) {
  51689. var _this = _super.call(this, name, source.getScene()) || this;
  51690. source.instances.push(_this);
  51691. _this._sourceMesh = source;
  51692. _this.position.copyFrom(source.position);
  51693. _this.rotation.copyFrom(source.rotation);
  51694. _this.scaling.copyFrom(source.scaling);
  51695. if (source.rotationQuaternion) {
  51696. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51697. }
  51698. _this.infiniteDistance = source.infiniteDistance;
  51699. _this.setPivotMatrix(source.getPivotMatrix());
  51700. _this.refreshBoundingInfo();
  51701. _this._syncSubMeshes();
  51702. return _this;
  51703. }
  51704. /**
  51705. * Returns the string "InstancedMesh".
  51706. */
  51707. InstancedMesh.prototype.getClassName = function () {
  51708. return "InstancedMesh";
  51709. };
  51710. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51711. // Methods
  51712. get: function () {
  51713. return this._sourceMesh.receiveShadows;
  51714. },
  51715. enumerable: true,
  51716. configurable: true
  51717. });
  51718. Object.defineProperty(InstancedMesh.prototype, "material", {
  51719. get: function () {
  51720. return this._sourceMesh.material;
  51721. },
  51722. enumerable: true,
  51723. configurable: true
  51724. });
  51725. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51726. get: function () {
  51727. return this._sourceMesh.visibility;
  51728. },
  51729. enumerable: true,
  51730. configurable: true
  51731. });
  51732. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51733. get: function () {
  51734. return this._sourceMesh.skeleton;
  51735. },
  51736. enumerable: true,
  51737. configurable: true
  51738. });
  51739. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51740. get: function () {
  51741. return this._sourceMesh.renderingGroupId;
  51742. },
  51743. enumerable: true,
  51744. configurable: true
  51745. });
  51746. /**
  51747. * Returns the total number of vertices (integer).
  51748. */
  51749. InstancedMesh.prototype.getTotalVertices = function () {
  51750. return this._sourceMesh.getTotalVertices();
  51751. };
  51752. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51753. get: function () {
  51754. return this._sourceMesh;
  51755. },
  51756. enumerable: true,
  51757. configurable: true
  51758. });
  51759. /**
  51760. * Is this node ready to be used/rendered
  51761. * @return {boolean} is it ready
  51762. */
  51763. InstancedMesh.prototype.isReady = function () {
  51764. return this._sourceMesh.isReady(true);
  51765. };
  51766. /**
  51767. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51768. */
  51769. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51770. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51771. };
  51772. /**
  51773. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51774. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51775. * The `data` are either a numeric array either a Float32Array.
  51776. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51777. * 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).
  51778. * Note that a new underlying VertexBuffer object is created each call.
  51779. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51780. *
  51781. * Possible `kind` values :
  51782. * - BABYLON.VertexBuffer.PositionKind
  51783. * - BABYLON.VertexBuffer.UVKind
  51784. * - BABYLON.VertexBuffer.UV2Kind
  51785. * - BABYLON.VertexBuffer.UV3Kind
  51786. * - BABYLON.VertexBuffer.UV4Kind
  51787. * - BABYLON.VertexBuffer.UV5Kind
  51788. * - BABYLON.VertexBuffer.UV6Kind
  51789. * - BABYLON.VertexBuffer.ColorKind
  51790. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51791. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51792. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51793. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51794. *
  51795. * Returns the Mesh.
  51796. */
  51797. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51798. if (this.sourceMesh) {
  51799. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51800. }
  51801. return this.sourceMesh;
  51802. };
  51803. /**
  51804. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51805. * If the mesh has no geometry, it is simply returned as it is.
  51806. * The `data` are either a numeric array either a Float32Array.
  51807. * No new underlying VertexBuffer object is created.
  51808. * 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.
  51809. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51810. *
  51811. * Possible `kind` values :
  51812. * - BABYLON.VertexBuffer.PositionKind
  51813. * - BABYLON.VertexBuffer.UVKind
  51814. * - BABYLON.VertexBuffer.UV2Kind
  51815. * - BABYLON.VertexBuffer.UV3Kind
  51816. * - BABYLON.VertexBuffer.UV4Kind
  51817. * - BABYLON.VertexBuffer.UV5Kind
  51818. * - BABYLON.VertexBuffer.UV6Kind
  51819. * - BABYLON.VertexBuffer.ColorKind
  51820. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51821. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51822. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51823. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51824. *
  51825. * Returns the Mesh.
  51826. */
  51827. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51828. if (this.sourceMesh) {
  51829. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51830. }
  51831. return this.sourceMesh;
  51832. };
  51833. /**
  51834. * Sets the mesh indices.
  51835. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51836. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51837. * This method creates a new index buffer each call.
  51838. * Returns the Mesh.
  51839. */
  51840. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51841. if (totalVertices === void 0) { totalVertices = null; }
  51842. if (this.sourceMesh) {
  51843. this.sourceMesh.setIndices(indices, totalVertices);
  51844. }
  51845. return this.sourceMesh;
  51846. };
  51847. /**
  51848. * Boolean : True if the mesh owns the requested kind of data.
  51849. */
  51850. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51851. return this._sourceMesh.isVerticesDataPresent(kind);
  51852. };
  51853. /**
  51854. * Returns an array of indices (IndicesArray).
  51855. */
  51856. InstancedMesh.prototype.getIndices = function () {
  51857. return this._sourceMesh.getIndices();
  51858. };
  51859. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51860. get: function () {
  51861. return this._sourceMesh._positions;
  51862. },
  51863. enumerable: true,
  51864. configurable: true
  51865. });
  51866. /**
  51867. * Sets a new updated BoundingInfo to the mesh.
  51868. * Returns the mesh.
  51869. */
  51870. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51871. var meshBB = this._sourceMesh.getBoundingInfo();
  51872. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51873. this._updateBoundingInfo();
  51874. return this;
  51875. };
  51876. InstancedMesh.prototype._preActivate = function () {
  51877. if (this._currentLOD) {
  51878. this._currentLOD._preActivate();
  51879. }
  51880. return this;
  51881. };
  51882. InstancedMesh.prototype._activate = function (renderId) {
  51883. if (this._currentLOD) {
  51884. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51885. }
  51886. return this;
  51887. };
  51888. /**
  51889. * Returns the current associated LOD AbstractMesh.
  51890. */
  51891. InstancedMesh.prototype.getLOD = function (camera) {
  51892. if (!camera) {
  51893. return this;
  51894. }
  51895. var boundingInfo = this.getBoundingInfo();
  51896. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51897. if (this._currentLOD === this.sourceMesh) {
  51898. return this;
  51899. }
  51900. return this._currentLOD;
  51901. };
  51902. InstancedMesh.prototype._syncSubMeshes = function () {
  51903. this.releaseSubMeshes();
  51904. if (this._sourceMesh.subMeshes) {
  51905. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51906. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51907. }
  51908. }
  51909. return this;
  51910. };
  51911. InstancedMesh.prototype._generatePointsArray = function () {
  51912. return this._sourceMesh._generatePointsArray();
  51913. };
  51914. /**
  51915. * Creates a new InstancedMesh from the current mesh.
  51916. * - name (string) : the cloned mesh name
  51917. * - newParent (optional Node) : the optional Node to parent the clone to.
  51918. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51919. *
  51920. * Returns the clone.
  51921. */
  51922. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51923. var result = this._sourceMesh.createInstance(name);
  51924. // Deep copy
  51925. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51926. // Bounding info
  51927. this.refreshBoundingInfo();
  51928. // Parent
  51929. if (newParent) {
  51930. result.parent = newParent;
  51931. }
  51932. if (!doNotCloneChildren) {
  51933. // Children
  51934. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51935. var mesh = this.getScene().meshes[index];
  51936. if (mesh.parent === this) {
  51937. mesh.clone(mesh.name, result);
  51938. }
  51939. }
  51940. }
  51941. result.computeWorldMatrix(true);
  51942. return result;
  51943. };
  51944. /**
  51945. * Disposes the InstancedMesh.
  51946. * Returns nothing.
  51947. */
  51948. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51949. // Remove from mesh
  51950. var index = this._sourceMesh.instances.indexOf(this);
  51951. this._sourceMesh.instances.splice(index, 1);
  51952. _super.prototype.dispose.call(this, doNotRecurse);
  51953. };
  51954. return InstancedMesh;
  51955. }(BABYLON.AbstractMesh));
  51956. BABYLON.InstancedMesh = InstancedMesh;
  51957. })(BABYLON || (BABYLON = {}));
  51958. //# sourceMappingURL=babylon.instancedMesh.js.map
  51959. var BABYLON;
  51960. (function (BABYLON) {
  51961. var LinesMesh = /** @class */ (function (_super) {
  51962. __extends(LinesMesh, _super);
  51963. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51964. if (scene === void 0) { scene = null; }
  51965. if (parent === void 0) { parent = null; }
  51966. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51967. _this.useVertexColor = useVertexColor;
  51968. _this.useVertexAlpha = useVertexAlpha;
  51969. _this.color = new BABYLON.Color3(1, 1, 1);
  51970. _this.alpha = 1;
  51971. if (source) {
  51972. _this.color = source.color.clone();
  51973. _this.alpha = source.alpha;
  51974. _this.useVertexColor = source.useVertexColor;
  51975. _this.useVertexAlpha = source.useVertexAlpha;
  51976. }
  51977. _this._intersectionThreshold = 0.1;
  51978. var defines = [];
  51979. var options = {
  51980. attributes: [BABYLON.VertexBuffer.PositionKind],
  51981. uniforms: ["world", "viewProjection"],
  51982. needAlphaBlending: true,
  51983. defines: defines
  51984. };
  51985. if (useVertexAlpha === false) {
  51986. options.needAlphaBlending = false;
  51987. }
  51988. if (!useVertexColor) {
  51989. options.uniforms.push("color");
  51990. }
  51991. else {
  51992. options.defines.push("#define VERTEXCOLOR");
  51993. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51994. }
  51995. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51996. return _this;
  51997. }
  51998. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51999. /**
  52000. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52001. * This margin is expressed in world space coordinates, so its value may vary.
  52002. * Default value is 0.1
  52003. * @returns the intersection Threshold value.
  52004. */
  52005. get: function () {
  52006. return this._intersectionThreshold;
  52007. },
  52008. /**
  52009. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52010. * This margin is expressed in world space coordinates, so its value may vary.
  52011. * @param value the new threshold to apply
  52012. */
  52013. set: function (value) {
  52014. if (this._intersectionThreshold === value) {
  52015. return;
  52016. }
  52017. this._intersectionThreshold = value;
  52018. if (this.geometry) {
  52019. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  52020. }
  52021. },
  52022. enumerable: true,
  52023. configurable: true
  52024. });
  52025. /**
  52026. * Returns the string "LineMesh"
  52027. */
  52028. LinesMesh.prototype.getClassName = function () {
  52029. return "LinesMesh";
  52030. };
  52031. Object.defineProperty(LinesMesh.prototype, "material", {
  52032. get: function () {
  52033. return this._colorShader;
  52034. },
  52035. set: function (value) {
  52036. // Do nothing
  52037. },
  52038. enumerable: true,
  52039. configurable: true
  52040. });
  52041. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  52042. get: function () {
  52043. return false;
  52044. },
  52045. enumerable: true,
  52046. configurable: true
  52047. });
  52048. LinesMesh.prototype.createInstance = function (name) {
  52049. throw new Error("LinesMeshes do not support createInstance.");
  52050. };
  52051. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  52052. if (!this._geometry) {
  52053. return this;
  52054. }
  52055. // VBOs
  52056. this._geometry._bind(this._colorShader.getEffect());
  52057. // Color
  52058. if (!this.useVertexColor) {
  52059. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  52060. }
  52061. return this;
  52062. };
  52063. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  52064. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  52065. return this;
  52066. }
  52067. var engine = this.getScene().getEngine();
  52068. // Draw order
  52069. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  52070. return this;
  52071. };
  52072. LinesMesh.prototype.dispose = function (doNotRecurse) {
  52073. this._colorShader.dispose();
  52074. _super.prototype.dispose.call(this, doNotRecurse);
  52075. };
  52076. /**
  52077. * Returns a new LineMesh object cloned from the current one.
  52078. */
  52079. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  52080. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  52081. };
  52082. return LinesMesh;
  52083. }(BABYLON.Mesh));
  52084. BABYLON.LinesMesh = LinesMesh;
  52085. })(BABYLON || (BABYLON = {}));
  52086. //# sourceMappingURL=babylon.linesMesh.js.map
  52087. var BABYLON;
  52088. (function (BABYLON) {
  52089. var MeshBuilder = /** @class */ (function () {
  52090. function MeshBuilder() {
  52091. }
  52092. MeshBuilder.updateSideOrientation = function (orientation) {
  52093. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  52094. return BABYLON.Mesh.DOUBLESIDE;
  52095. }
  52096. if (orientation === undefined || orientation === null) {
  52097. return BABYLON.Mesh.FRONTSIDE;
  52098. }
  52099. return orientation;
  52100. };
  52101. /**
  52102. * Creates a box mesh.
  52103. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  52104. * The parameter `size` sets the size (float) of each box side (default 1).
  52105. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  52106. * 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).
  52107. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52108. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52109. * 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).
  52110. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52112. */
  52113. MeshBuilder.CreateBox = function (name, options, scene) {
  52114. if (scene === void 0) { scene = null; }
  52115. var box = new BABYLON.Mesh(name, scene);
  52116. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52117. box._originalBuilderSideOrientation = options.sideOrientation;
  52118. var vertexData = BABYLON.VertexData.CreateBox(options);
  52119. vertexData.applyToMesh(box, options.updatable);
  52120. return box;
  52121. };
  52122. /**
  52123. * Creates a sphere mesh.
  52124. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  52125. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  52126. * 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`).
  52127. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  52128. * 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
  52129. * 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).
  52130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52131. * 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).
  52132. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52134. */
  52135. MeshBuilder.CreateSphere = function (name, options, scene) {
  52136. var sphere = new BABYLON.Mesh(name, scene);
  52137. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52138. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52139. var vertexData = BABYLON.VertexData.CreateSphere(options);
  52140. vertexData.applyToMesh(sphere, options.updatable);
  52141. return sphere;
  52142. };
  52143. /**
  52144. * Creates a plane polygonal mesh. By default, this is a disc.
  52145. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  52146. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  52147. * 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.
  52148. * 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
  52149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52150. * 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).
  52151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52153. */
  52154. MeshBuilder.CreateDisc = function (name, options, scene) {
  52155. if (scene === void 0) { scene = null; }
  52156. var disc = new BABYLON.Mesh(name, scene);
  52157. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52158. disc._originalBuilderSideOrientation = options.sideOrientation;
  52159. var vertexData = BABYLON.VertexData.CreateDisc(options);
  52160. vertexData.applyToMesh(disc, options.updatable);
  52161. return disc;
  52162. };
  52163. /**
  52164. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  52165. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  52166. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  52167. * 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`).
  52168. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  52169. * 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.
  52170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52171. * 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).
  52172. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52174. */
  52175. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  52176. var sphere = new BABYLON.Mesh(name, scene);
  52177. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52178. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52179. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  52180. vertexData.applyToMesh(sphere, options.updatable);
  52181. return sphere;
  52182. };
  52183. ;
  52184. /**
  52185. * Creates a ribbon mesh.
  52186. * 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.
  52187. *
  52188. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  52189. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  52190. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  52191. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  52192. * 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.
  52193. * 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.
  52194. * 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
  52195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52196. * 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).
  52197. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52198. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52199. * 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.
  52200. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  52201. * 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
  52202. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  52203. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  52204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52205. */
  52206. MeshBuilder.CreateRibbon = function (name, options, scene) {
  52207. if (scene === void 0) { scene = null; }
  52208. var pathArray = options.pathArray;
  52209. var closeArray = options.closeArray;
  52210. var closePath = options.closePath;
  52211. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52212. var instance = options.instance;
  52213. var updatable = options.updatable;
  52214. if (instance) {
  52215. // positionFunction : ribbon case
  52216. // only pathArray and sideOrientation parameters are taken into account for positions update
  52217. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  52218. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  52219. var positionFunction = function (positions) {
  52220. var minlg = pathArray[0].length;
  52221. var i = 0;
  52222. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  52223. for (var si = 1; si <= ns; si++) {
  52224. for (var p = 0; p < pathArray.length; p++) {
  52225. var path = pathArray[p];
  52226. var l = path.length;
  52227. minlg = (minlg < l) ? minlg : l;
  52228. var j = 0;
  52229. while (j < minlg) {
  52230. positions[i] = path[j].x;
  52231. positions[i + 1] = path[j].y;
  52232. positions[i + 2] = path[j].z;
  52233. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  52234. BABYLON.Tmp.Vector3[0].x = path[j].x;
  52235. }
  52236. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  52237. BABYLON.Tmp.Vector3[1].x = path[j].x;
  52238. }
  52239. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  52240. BABYLON.Tmp.Vector3[0].y = path[j].y;
  52241. }
  52242. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  52243. BABYLON.Tmp.Vector3[1].y = path[j].y;
  52244. }
  52245. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  52246. BABYLON.Tmp.Vector3[0].z = path[j].z;
  52247. }
  52248. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  52249. BABYLON.Tmp.Vector3[1].z = path[j].z;
  52250. }
  52251. j++;
  52252. i += 3;
  52253. }
  52254. if (instance._closePath) {
  52255. positions[i] = path[0].x;
  52256. positions[i + 1] = path[0].y;
  52257. positions[i + 2] = path[0].z;
  52258. i += 3;
  52259. }
  52260. }
  52261. }
  52262. };
  52263. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52264. positionFunction(positions);
  52265. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  52266. instance._boundingInfo.update(instance._worldMatrix);
  52267. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52268. if (options.colors) {
  52269. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52270. for (var c = 0; c < options.colors.length; c++) {
  52271. colors[c * 4] = options.colors[c].r;
  52272. colors[c * 4 + 1] = options.colors[c].g;
  52273. colors[c * 4 + 2] = options.colors[c].b;
  52274. colors[c * 4 + 3] = options.colors[c].a;
  52275. }
  52276. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  52277. }
  52278. if (options.uvs) {
  52279. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52280. for (var i = 0; i < options.uvs.length; i++) {
  52281. uvs[i * 2] = options.uvs[i].x;
  52282. uvs[i * 2 + 1] = options.uvs[i].y;
  52283. }
  52284. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  52285. }
  52286. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  52287. var indices = instance.getIndices();
  52288. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52289. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  52290. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  52291. if (instance._closePath) {
  52292. var indexFirst = 0;
  52293. var indexLast = 0;
  52294. for (var p = 0; p < pathArray.length; p++) {
  52295. indexFirst = instance._idx[p] * 3;
  52296. if (p + 1 < pathArray.length) {
  52297. indexLast = (instance._idx[p + 1] - 1) * 3;
  52298. }
  52299. else {
  52300. indexLast = normals.length - 3;
  52301. }
  52302. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  52303. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  52304. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  52305. normals[indexLast] = normals[indexFirst];
  52306. normals[indexLast + 1] = normals[indexFirst + 1];
  52307. normals[indexLast + 2] = normals[indexFirst + 2];
  52308. }
  52309. }
  52310. if (!(instance.areNormalsFrozen)) {
  52311. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  52312. }
  52313. }
  52314. return instance;
  52315. }
  52316. else {
  52317. var ribbon = new BABYLON.Mesh(name, scene);
  52318. ribbon._originalBuilderSideOrientation = sideOrientation;
  52319. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  52320. if (closePath) {
  52321. ribbon._idx = vertexData._idx;
  52322. }
  52323. ribbon._closePath = closePath;
  52324. ribbon._closeArray = closeArray;
  52325. vertexData.applyToMesh(ribbon, updatable);
  52326. return ribbon;
  52327. }
  52328. };
  52329. /**
  52330. * Creates a cylinder or a cone mesh.
  52331. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  52332. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  52333. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  52334. * 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.
  52335. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  52336. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  52337. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  52338. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  52339. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  52340. * 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).
  52341. * 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
  52342. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  52343. * 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
  52344. * 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.
  52345. * If `enclose` is false, a ring surface is one element.
  52346. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  52347. * 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
  52348. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52349. * 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).
  52350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52352. */
  52353. MeshBuilder.CreateCylinder = function (name, options, scene) {
  52354. var cylinder = new BABYLON.Mesh(name, scene);
  52355. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52356. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  52357. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  52358. vertexData.applyToMesh(cylinder, options.updatable);
  52359. return cylinder;
  52360. };
  52361. /**
  52362. * Creates a torus mesh.
  52363. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  52364. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  52365. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  52366. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  52367. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52368. * 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).
  52369. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52371. */
  52372. MeshBuilder.CreateTorus = function (name, options, scene) {
  52373. var torus = new BABYLON.Mesh(name, scene);
  52374. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52375. torus._originalBuilderSideOrientation = options.sideOrientation;
  52376. var vertexData = BABYLON.VertexData.CreateTorus(options);
  52377. vertexData.applyToMesh(torus, options.updatable);
  52378. return torus;
  52379. };
  52380. /**
  52381. * Creates a torus knot mesh.
  52382. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  52383. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  52384. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  52385. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  52386. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  52387. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52388. * 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).
  52389. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52391. */
  52392. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  52393. var torusKnot = new BABYLON.Mesh(name, scene);
  52394. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52395. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  52396. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  52397. vertexData.applyToMesh(torusKnot, options.updatable);
  52398. return torusKnot;
  52399. };
  52400. /**
  52401. * Creates a line system mesh.
  52402. * A line system is a pool of many lines gathered in a single mesh.
  52403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  52404. * 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.
  52405. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  52406. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  52407. * 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
  52408. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  52409. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  52410. * 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
  52411. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  52412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52413. */
  52414. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  52415. var instance = options.instance;
  52416. var lines = options.lines;
  52417. var colors = options.colors;
  52418. if (instance) {
  52419. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52420. var vertexColor;
  52421. var lineColors;
  52422. if (colors) {
  52423. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52424. }
  52425. var i = 0;
  52426. var c = 0;
  52427. for (var l = 0; l < lines.length; l++) {
  52428. var points = lines[l];
  52429. for (var p = 0; p < points.length; p++) {
  52430. positions[i] = points[p].x;
  52431. positions[i + 1] = points[p].y;
  52432. positions[i + 2] = points[p].z;
  52433. if (colors && vertexColor) {
  52434. lineColors = colors[l];
  52435. vertexColor[c] = lineColors[p].r;
  52436. vertexColor[c + 1] = lineColors[p].g;
  52437. vertexColor[c + 2] = lineColors[p].b;
  52438. vertexColor[c + 3] = lineColors[p].a;
  52439. c += 4;
  52440. }
  52441. i += 3;
  52442. }
  52443. }
  52444. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52445. if (colors && vertexColor) {
  52446. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  52447. }
  52448. return instance;
  52449. }
  52450. // line system creation
  52451. var useVertexColor = (colors) ? true : false;
  52452. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  52453. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  52454. vertexData.applyToMesh(lineSystem, options.updatable);
  52455. return lineSystem;
  52456. };
  52457. /**
  52458. * Creates a line mesh.
  52459. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  52460. * 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.
  52461. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52462. * The parameter `points` is an array successive Vector3.
  52463. * 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
  52464. * The optional parameter `colors` is an array of successive Color4, one per line point.
  52465. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  52466. * When updating an instance, remember that only point positions can change, not the number of points.
  52467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52468. */
  52469. MeshBuilder.CreateLines = function (name, options, scene) {
  52470. if (scene === void 0) { scene = null; }
  52471. var colors = (options.colors) ? [options.colors] : null;
  52472. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  52473. return lines;
  52474. };
  52475. /**
  52476. * Creates a dashed line mesh.
  52477. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  52478. * 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.
  52479. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52480. * The parameter `points` is an array successive Vector3.
  52481. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  52482. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  52483. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  52484. * 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
  52485. * When updating an instance, remember that only point positions can change, not the number of points.
  52486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52487. */
  52488. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  52489. if (scene === void 0) { scene = null; }
  52490. var points = options.points;
  52491. var instance = options.instance;
  52492. var gapSize = options.gapSize || 1;
  52493. var dashSize = options.dashSize || 3;
  52494. if (instance) {
  52495. var positionFunction = function (positions) {
  52496. var curvect = BABYLON.Vector3.Zero();
  52497. var nbSeg = positions.length / 6;
  52498. var lg = 0;
  52499. var nb = 0;
  52500. var shft = 0;
  52501. var dashshft = 0;
  52502. var curshft = 0;
  52503. var p = 0;
  52504. var i = 0;
  52505. var j = 0;
  52506. for (i = 0; i < points.length - 1; i++) {
  52507. points[i + 1].subtractToRef(points[i], curvect);
  52508. lg += curvect.length();
  52509. }
  52510. shft = lg / nbSeg;
  52511. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  52512. for (i = 0; i < points.length - 1; i++) {
  52513. points[i + 1].subtractToRef(points[i], curvect);
  52514. nb = Math.floor(curvect.length() / shft);
  52515. curvect.normalize();
  52516. j = 0;
  52517. while (j < nb && p < positions.length) {
  52518. curshft = shft * j;
  52519. positions[p] = points[i].x + curshft * curvect.x;
  52520. positions[p + 1] = points[i].y + curshft * curvect.y;
  52521. positions[p + 2] = points[i].z + curshft * curvect.z;
  52522. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  52523. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  52524. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  52525. p += 6;
  52526. j++;
  52527. }
  52528. }
  52529. while (p < positions.length) {
  52530. positions[p] = points[i].x;
  52531. positions[p + 1] = points[i].y;
  52532. positions[p + 2] = points[i].z;
  52533. p += 3;
  52534. }
  52535. };
  52536. instance.updateMeshPositions(positionFunction, false);
  52537. return instance;
  52538. }
  52539. // dashed lines creation
  52540. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52541. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52542. vertexData.applyToMesh(dashedLines, options.updatable);
  52543. dashedLines.dashSize = dashSize;
  52544. dashedLines.gapSize = gapSize;
  52545. return dashedLines;
  52546. };
  52547. /**
  52548. * Creates an extruded shape mesh.
  52549. * 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.
  52550. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52551. *
  52552. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52553. * 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
  52554. * extruded along the Z axis.
  52555. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52556. * 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.
  52557. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52558. * 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
  52559. * 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
  52560. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52562. * 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).
  52563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52564. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52566. */
  52567. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52568. if (scene === void 0) { scene = null; }
  52569. var path = options.path;
  52570. var shape = options.shape;
  52571. var scale = options.scale || 1;
  52572. var rotation = options.rotation || 0;
  52573. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52574. var updatable = options.updatable;
  52575. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52576. var instance = options.instance || null;
  52577. var invertUV = options.invertUV || false;
  52578. 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);
  52579. };
  52580. /**
  52581. * Creates an custom extruded shape mesh.
  52582. * 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.
  52583. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52584. *
  52585. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52586. * 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
  52587. * extruded along the Z axis.
  52588. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52589. * 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
  52590. * and the distance of this point from the begining of the path :
  52591. * ```javascript
  52592. * var rotationFunction = function(i, distance) {
  52593. * // do things
  52594. * return rotationValue; }
  52595. * ```
  52596. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52597. * 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
  52598. * and the distance of this point from the begining of the path :
  52599. * ```javascript
  52600. * var scaleFunction = function(i, distance) {
  52601. * // do things
  52602. * return scaleValue;}
  52603. * ```
  52604. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52605. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52606. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52607. * 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
  52608. * 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
  52609. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52611. * 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).
  52612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52613. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52615. */
  52616. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52617. var path = options.path;
  52618. var shape = options.shape;
  52619. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52620. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52621. var ribbonCloseArray = options.ribbonCloseArray || false;
  52622. var ribbonClosePath = options.ribbonClosePath || false;
  52623. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52624. var updatable = options.updatable;
  52625. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52626. var instance = options.instance;
  52627. var invertUV = options.invertUV || false;
  52628. 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);
  52629. };
  52630. /**
  52631. * Creates lathe mesh.
  52632. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52634. *
  52635. * 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
  52636. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52637. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52638. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52639. * 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.
  52640. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52641. * 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
  52642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52643. * 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).
  52644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52645. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52647. */
  52648. MeshBuilder.CreateLathe = function (name, options, scene) {
  52649. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52650. var closed = (options.closed === undefined) ? true : options.closed;
  52651. var shape = options.shape;
  52652. var radius = options.radius || 1;
  52653. var tessellation = options.tessellation || 64;
  52654. var updatable = options.updatable;
  52655. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52656. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52657. var pi2 = Math.PI * 2;
  52658. var paths = new Array();
  52659. var invertUV = options.invertUV || false;
  52660. var i = 0;
  52661. var p = 0;
  52662. var step = pi2 / tessellation * arc;
  52663. var rotated;
  52664. var path = new Array();
  52665. ;
  52666. for (i = 0; i <= tessellation; i++) {
  52667. var path = [];
  52668. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52669. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52670. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52671. }
  52672. for (p = 0; p < shape.length; p++) {
  52673. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52674. path.push(rotated);
  52675. }
  52676. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52677. 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));
  52678. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52679. }
  52680. paths.push(path);
  52681. }
  52682. // lathe ribbon
  52683. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52684. return lathe;
  52685. };
  52686. /**
  52687. * Creates a plane mesh.
  52688. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52689. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52690. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52691. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52693. * 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).
  52694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52696. */
  52697. MeshBuilder.CreatePlane = function (name, options, scene) {
  52698. var plane = new BABYLON.Mesh(name, scene);
  52699. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52700. plane._originalBuilderSideOrientation = options.sideOrientation;
  52701. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52702. vertexData.applyToMesh(plane, options.updatable);
  52703. if (options.sourcePlane) {
  52704. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52705. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52706. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52707. plane.rotate(vectorProduct, product);
  52708. }
  52709. return plane;
  52710. };
  52711. /**
  52712. * Creates a ground mesh.
  52713. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52714. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52715. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52717. */
  52718. MeshBuilder.CreateGround = function (name, options, scene) {
  52719. var ground = new BABYLON.GroundMesh(name, scene);
  52720. ground._setReady(false);
  52721. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52722. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52723. ground._width = options.width || 1;
  52724. ground._height = options.height || 1;
  52725. ground._maxX = ground._width / 2;
  52726. ground._maxZ = ground._height / 2;
  52727. ground._minX = -ground._maxX;
  52728. ground._minZ = -ground._maxZ;
  52729. var vertexData = BABYLON.VertexData.CreateGround(options);
  52730. vertexData.applyToMesh(ground, options.updatable);
  52731. ground._setReady(true);
  52732. return ground;
  52733. };
  52734. /**
  52735. * Creates a tiled ground mesh.
  52736. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52737. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52738. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52739. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52740. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52741. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52742. * numbers of subdivisions on the ground width and height of each tile.
  52743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52744. */
  52745. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52746. var tiledGround = new BABYLON.Mesh(name, scene);
  52747. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52748. vertexData.applyToMesh(tiledGround, options.updatable);
  52749. return tiledGround;
  52750. };
  52751. /**
  52752. * Creates a ground mesh from a height map.
  52753. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52754. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52755. * The parameter `url` sets the URL of the height map image resource.
  52756. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52757. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52758. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52759. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52760. * 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.
  52761. * 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).
  52762. * This function is passed the newly built mesh :
  52763. * ```javascript
  52764. * function(mesh) { // do things
  52765. * return; }
  52766. * ```
  52767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52768. */
  52769. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52770. var width = options.width || 10.0;
  52771. var height = options.height || 10.0;
  52772. var subdivisions = options.subdivisions || 1 | 0;
  52773. var minHeight = options.minHeight || 0.0;
  52774. var maxHeight = options.maxHeight || 1.0;
  52775. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52776. var updatable = options.updatable;
  52777. var onReady = options.onReady;
  52778. var ground = new BABYLON.GroundMesh(name, scene);
  52779. ground._subdivisionsX = subdivisions;
  52780. ground._subdivisionsY = subdivisions;
  52781. ground._width = width;
  52782. ground._height = height;
  52783. ground._maxX = ground._width / 2.0;
  52784. ground._maxZ = ground._height / 2.0;
  52785. ground._minX = -ground._maxX;
  52786. ground._minZ = -ground._maxZ;
  52787. ground._setReady(false);
  52788. var onload = function (img) {
  52789. // Getting height map data
  52790. var canvas = document.createElement("canvas");
  52791. var context = canvas.getContext("2d");
  52792. if (!context) {
  52793. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52794. }
  52795. if (scene.isDisposed) {
  52796. return;
  52797. }
  52798. var bufferWidth = img.width;
  52799. var bufferHeight = img.height;
  52800. canvas.width = bufferWidth;
  52801. canvas.height = bufferHeight;
  52802. context.drawImage(img, 0, 0);
  52803. // Create VertexData from map data
  52804. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52805. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52806. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52807. width: width, height: height,
  52808. subdivisions: subdivisions,
  52809. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52810. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52811. });
  52812. vertexData.applyToMesh(ground, updatable);
  52813. ground._setReady(true);
  52814. //execute ready callback, if set
  52815. if (onReady) {
  52816. onReady(ground);
  52817. }
  52818. };
  52819. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52820. return ground;
  52821. };
  52822. /**
  52823. * Creates a polygon mesh.
  52824. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52825. * 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.
  52826. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52828. * 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).
  52829. * Remember you can only change the shape positions, not their number when updating a polygon.
  52830. */
  52831. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52832. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52833. var shape = options.shape;
  52834. var holes = options.holes || [];
  52835. var depth = options.depth || 0;
  52836. var contours = [];
  52837. var hole = [];
  52838. for (var i = 0; i < shape.length; i++) {
  52839. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52840. }
  52841. var epsilon = 0.00000001;
  52842. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52843. contours.pop();
  52844. }
  52845. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52846. for (var hNb = 0; hNb < holes.length; hNb++) {
  52847. hole = [];
  52848. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52849. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52850. }
  52851. polygonTriangulation.addHole(hole);
  52852. }
  52853. var polygon = polygonTriangulation.build(options.updatable, depth);
  52854. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52855. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52856. vertexData.applyToMesh(polygon, options.updatable);
  52857. return polygon;
  52858. };
  52859. ;
  52860. /**
  52861. * Creates an extruded polygon mesh, with depth in the Y direction.
  52862. * 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).
  52863. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52864. */
  52865. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52866. return MeshBuilder.CreatePolygon(name, options, scene);
  52867. };
  52868. ;
  52869. /**
  52870. * Creates a tube mesh.
  52871. * 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.
  52872. *
  52873. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52874. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52875. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52876. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52877. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52878. * 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.
  52879. * It must return a radius value (positive float) :
  52880. * ```javascript
  52881. * var radiusFunction = function(i, distance) {
  52882. * // do things
  52883. * return radius; }
  52884. * ```
  52885. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52886. * 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
  52887. * 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
  52888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52889. * 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).
  52890. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52891. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52893. */
  52894. MeshBuilder.CreateTube = function (name, options, scene) {
  52895. var path = options.path;
  52896. var instance = options.instance;
  52897. var radius = 1.0;
  52898. if (instance) {
  52899. radius = instance.radius;
  52900. }
  52901. if (options.radius !== undefined) {
  52902. radius = options.radius;
  52903. }
  52904. ;
  52905. var tessellation = options.tessellation || 64 | 0;
  52906. var radiusFunction = options.radiusFunction || null;
  52907. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52908. var invertUV = options.invertUV || false;
  52909. var updatable = options.updatable;
  52910. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52911. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52912. // tube geometry
  52913. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52914. var tangents = path3D.getTangents();
  52915. var normals = path3D.getNormals();
  52916. var distances = path3D.getDistances();
  52917. var pi2 = Math.PI * 2;
  52918. var step = pi2 / tessellation * arc;
  52919. var returnRadius = function () { return radius; };
  52920. var radiusFunctionFinal = radiusFunction || returnRadius;
  52921. var circlePath;
  52922. var rad;
  52923. var normal;
  52924. var rotated;
  52925. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52926. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52927. for (var i = 0; i < path.length; i++) {
  52928. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52929. circlePath = Array(); // current circle array
  52930. normal = normals[i]; // current normal
  52931. for (var t = 0; t < tessellation; t++) {
  52932. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52933. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52934. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52935. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52936. circlePath[t] = rotated;
  52937. }
  52938. circlePaths[index] = circlePath;
  52939. index++;
  52940. }
  52941. // cap
  52942. var capPath = function (nbPoints, pathIndex) {
  52943. var pointCap = Array();
  52944. for (var i = 0; i < nbPoints; i++) {
  52945. pointCap.push(path[pathIndex]);
  52946. }
  52947. return pointCap;
  52948. };
  52949. switch (cap) {
  52950. case BABYLON.Mesh.NO_CAP:
  52951. break;
  52952. case BABYLON.Mesh.CAP_START:
  52953. circlePaths[0] = capPath(tessellation, 0);
  52954. circlePaths[1] = circlePaths[2].slice(0);
  52955. break;
  52956. case BABYLON.Mesh.CAP_END:
  52957. circlePaths[index] = circlePaths[index - 1].slice(0);
  52958. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52959. break;
  52960. case BABYLON.Mesh.CAP_ALL:
  52961. circlePaths[0] = capPath(tessellation, 0);
  52962. circlePaths[1] = circlePaths[2].slice(0);
  52963. circlePaths[index] = circlePaths[index - 1].slice(0);
  52964. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52965. break;
  52966. default:
  52967. break;
  52968. }
  52969. return circlePaths;
  52970. };
  52971. var path3D;
  52972. var pathArray;
  52973. if (instance) {
  52974. var arc = options.arc || instance.arc;
  52975. path3D = (instance.path3D).update(path);
  52976. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52977. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52978. instance.path3D = path3D;
  52979. instance.pathArray = pathArray;
  52980. instance.arc = arc;
  52981. instance.radius = radius;
  52982. return instance;
  52983. }
  52984. // tube creation
  52985. path3D = new BABYLON.Path3D(path);
  52986. var newPathArray = new Array();
  52987. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52988. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52989. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52990. tube.pathArray = pathArray;
  52991. tube.path3D = path3D;
  52992. tube.tessellation = tessellation;
  52993. tube.cap = cap;
  52994. tube.arc = options.arc;
  52995. tube.radius = radius;
  52996. return tube;
  52997. };
  52998. /**
  52999. * Creates a polyhedron mesh.
  53000. *
  53001. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  53002. * 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
  53003. * to choose the wanted type.
  53004. * The parameter `size` (positive float, default 1) sets the polygon size.
  53005. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  53006. * 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`.
  53007. * 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
  53008. * 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)`).
  53009. * 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
  53010. * 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.
  53011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53012. * 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).
  53013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53015. */
  53016. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  53017. var polyhedron = new BABYLON.Mesh(name, scene);
  53018. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53019. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  53020. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  53021. vertexData.applyToMesh(polyhedron, options.updatable);
  53022. return polyhedron;
  53023. };
  53024. /**
  53025. * Creates a decal mesh.
  53026. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  53027. * 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.
  53028. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  53029. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  53030. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  53031. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  53032. */
  53033. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  53034. var indices = sourceMesh.getIndices();
  53035. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53036. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53037. var position = options.position || BABYLON.Vector3.Zero();
  53038. var normal = options.normal || BABYLON.Vector3.Up();
  53039. var size = options.size || BABYLON.Vector3.One();
  53040. var angle = options.angle || 0;
  53041. // Getting correct rotation
  53042. if (!normal) {
  53043. var target = new BABYLON.Vector3(0, 0, 1);
  53044. var camera = sourceMesh.getScene().activeCamera;
  53045. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  53046. normal = camera.globalPosition.subtract(cameraWorldTarget);
  53047. }
  53048. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  53049. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  53050. var pitch = Math.atan2(normal.y, len);
  53051. // Matrix
  53052. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  53053. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  53054. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  53055. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  53056. var vertexData = new BABYLON.VertexData();
  53057. vertexData.indices = [];
  53058. vertexData.positions = [];
  53059. vertexData.normals = [];
  53060. vertexData.uvs = [];
  53061. var currentVertexDataIndex = 0;
  53062. var extractDecalVector3 = function (indexId) {
  53063. var result = new BABYLON.PositionNormalVertex();
  53064. if (!indices || !positions || !normals) {
  53065. return result;
  53066. }
  53067. var vertexId = indices[indexId];
  53068. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  53069. // Send vector to decal local world
  53070. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  53071. // Get normal
  53072. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  53073. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  53074. return result;
  53075. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  53076. var clip = function (vertices, axis) {
  53077. if (vertices.length === 0) {
  53078. return vertices;
  53079. }
  53080. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  53081. var clipVertices = function (v0, v1) {
  53082. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  53083. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  53084. };
  53085. var result = new Array();
  53086. for (var index = 0; index < vertices.length; index += 3) {
  53087. var v1Out;
  53088. var v2Out;
  53089. var v3Out;
  53090. var total = 0;
  53091. var nV1 = null;
  53092. var nV2 = null;
  53093. var nV3 = null;
  53094. var nV4 = null;
  53095. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  53096. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  53097. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  53098. v1Out = d1 > 0;
  53099. v2Out = d2 > 0;
  53100. v3Out = d3 > 0;
  53101. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  53102. switch (total) {
  53103. case 0:
  53104. result.push(vertices[index]);
  53105. result.push(vertices[index + 1]);
  53106. result.push(vertices[index + 2]);
  53107. break;
  53108. case 1:
  53109. if (v1Out) {
  53110. nV1 = vertices[index + 1];
  53111. nV2 = vertices[index + 2];
  53112. nV3 = clipVertices(vertices[index], nV1);
  53113. nV4 = clipVertices(vertices[index], nV2);
  53114. }
  53115. if (v2Out) {
  53116. nV1 = vertices[index];
  53117. nV2 = vertices[index + 2];
  53118. nV3 = clipVertices(vertices[index + 1], nV1);
  53119. nV4 = clipVertices(vertices[index + 1], nV2);
  53120. result.push(nV3);
  53121. result.push(nV2.clone());
  53122. result.push(nV1.clone());
  53123. result.push(nV2.clone());
  53124. result.push(nV3.clone());
  53125. result.push(nV4);
  53126. break;
  53127. }
  53128. if (v3Out) {
  53129. nV1 = vertices[index];
  53130. nV2 = vertices[index + 1];
  53131. nV3 = clipVertices(vertices[index + 2], nV1);
  53132. nV4 = clipVertices(vertices[index + 2], nV2);
  53133. }
  53134. if (nV1 && nV2 && nV3 && nV4) {
  53135. result.push(nV1.clone());
  53136. result.push(nV2.clone());
  53137. result.push(nV3);
  53138. result.push(nV4);
  53139. result.push(nV3.clone());
  53140. result.push(nV2.clone());
  53141. }
  53142. break;
  53143. case 2:
  53144. if (!v1Out) {
  53145. nV1 = vertices[index].clone();
  53146. nV2 = clipVertices(nV1, vertices[index + 1]);
  53147. nV3 = clipVertices(nV1, vertices[index + 2]);
  53148. result.push(nV1);
  53149. result.push(nV2);
  53150. result.push(nV3);
  53151. }
  53152. if (!v2Out) {
  53153. nV1 = vertices[index + 1].clone();
  53154. nV2 = clipVertices(nV1, vertices[index + 2]);
  53155. nV3 = clipVertices(nV1, vertices[index]);
  53156. result.push(nV1);
  53157. result.push(nV2);
  53158. result.push(nV3);
  53159. }
  53160. if (!v3Out) {
  53161. nV1 = vertices[index + 2].clone();
  53162. nV2 = clipVertices(nV1, vertices[index]);
  53163. nV3 = clipVertices(nV1, vertices[index + 1]);
  53164. result.push(nV1);
  53165. result.push(nV2);
  53166. result.push(nV3);
  53167. }
  53168. break;
  53169. case 3:
  53170. break;
  53171. }
  53172. }
  53173. return result;
  53174. };
  53175. for (var index = 0; index < indices.length; index += 3) {
  53176. var faceVertices = new Array();
  53177. faceVertices.push(extractDecalVector3(index));
  53178. faceVertices.push(extractDecalVector3(index + 1));
  53179. faceVertices.push(extractDecalVector3(index + 2));
  53180. // Clip
  53181. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  53182. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  53183. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  53184. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  53185. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  53186. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  53187. if (faceVertices.length === 0) {
  53188. continue;
  53189. }
  53190. // Add UVs and get back to world
  53191. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  53192. var vertex = faceVertices[vIndex];
  53193. //TODO check for Int32Array | Uint32Array | Uint16Array
  53194. vertexData.indices.push(currentVertexDataIndex);
  53195. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  53196. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  53197. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  53198. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  53199. currentVertexDataIndex++;
  53200. }
  53201. }
  53202. // Return mesh
  53203. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  53204. vertexData.applyToMesh(decal);
  53205. decal.position = position.clone();
  53206. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  53207. return decal;
  53208. };
  53209. // Privates
  53210. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  53211. // extrusion geometry
  53212. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  53213. var tangents = path3D.getTangents();
  53214. var normals = path3D.getNormals();
  53215. var binormals = path3D.getBinormals();
  53216. var distances = path3D.getDistances();
  53217. var angle = 0;
  53218. var returnScale = function () { return scale !== null ? scale : 1; };
  53219. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  53220. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  53221. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  53222. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53223. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53224. for (var i = 0; i < curve.length; i++) {
  53225. var shapePath = new Array();
  53226. var angleStep = rotate(i, distances[i]);
  53227. var scaleRatio = scl(i, distances[i]);
  53228. for (var p = 0; p < shape.length; p++) {
  53229. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  53230. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  53231. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  53232. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  53233. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  53234. shapePath[p] = rotated;
  53235. }
  53236. shapePaths[index] = shapePath;
  53237. angle += angleStep;
  53238. index++;
  53239. }
  53240. // cap
  53241. var capPath = function (shapePath) {
  53242. var pointCap = Array();
  53243. var barycenter = BABYLON.Vector3.Zero();
  53244. var i;
  53245. for (i = 0; i < shapePath.length; i++) {
  53246. barycenter.addInPlace(shapePath[i]);
  53247. }
  53248. barycenter.scaleInPlace(1.0 / shapePath.length);
  53249. for (i = 0; i < shapePath.length; i++) {
  53250. pointCap.push(barycenter);
  53251. }
  53252. return pointCap;
  53253. };
  53254. switch (cap) {
  53255. case BABYLON.Mesh.NO_CAP:
  53256. break;
  53257. case BABYLON.Mesh.CAP_START:
  53258. shapePaths[0] = capPath(shapePaths[2]);
  53259. shapePaths[1] = shapePaths[2];
  53260. break;
  53261. case BABYLON.Mesh.CAP_END:
  53262. shapePaths[index] = shapePaths[index - 1];
  53263. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53264. break;
  53265. case BABYLON.Mesh.CAP_ALL:
  53266. shapePaths[0] = capPath(shapePaths[2]);
  53267. shapePaths[1] = shapePaths[2];
  53268. shapePaths[index] = shapePaths[index - 1];
  53269. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53270. break;
  53271. default:
  53272. break;
  53273. }
  53274. return shapePaths;
  53275. };
  53276. var path3D;
  53277. var pathArray;
  53278. if (instance) {
  53279. path3D = (instance.path3D).update(curve);
  53280. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  53281. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  53282. return instance;
  53283. }
  53284. // extruded shape creation
  53285. path3D = new BABYLON.Path3D(curve);
  53286. var newShapePaths = new Array();
  53287. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53288. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  53289. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  53290. extrudedGeneric.pathArray = pathArray;
  53291. extrudedGeneric.path3D = path3D;
  53292. extrudedGeneric.cap = cap;
  53293. return extrudedGeneric;
  53294. };
  53295. return MeshBuilder;
  53296. }());
  53297. BABYLON.MeshBuilder = MeshBuilder;
  53298. })(BABYLON || (BABYLON = {}));
  53299. //# sourceMappingURL=babylon.meshBuilder.js.map
  53300. var BABYLON;
  53301. (function (BABYLON) {
  53302. var AudioEngine = /** @class */ (function () {
  53303. function AudioEngine() {
  53304. this._audioContext = null;
  53305. this._audioContextInitialized = false;
  53306. this.canUseWebAudio = false;
  53307. this.WarnedWebAudioUnsupported = false;
  53308. this.unlocked = false;
  53309. this.isMP3supported = false;
  53310. this.isOGGsupported = false;
  53311. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  53312. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  53313. this.canUseWebAudio = true;
  53314. }
  53315. var audioElem = document.createElement('audio');
  53316. try {
  53317. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  53318. this.isMP3supported = true;
  53319. }
  53320. }
  53321. catch (e) {
  53322. // protect error during capability check.
  53323. }
  53324. try {
  53325. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  53326. this.isOGGsupported = true;
  53327. }
  53328. }
  53329. catch (e) {
  53330. // protect error during capability check.
  53331. }
  53332. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  53333. this._unlockiOSaudio();
  53334. }
  53335. else {
  53336. this.unlocked = true;
  53337. }
  53338. }
  53339. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  53340. get: function () {
  53341. if (!this._audioContextInitialized) {
  53342. this._initializeAudioContext();
  53343. }
  53344. return this._audioContext;
  53345. },
  53346. enumerable: true,
  53347. configurable: true
  53348. });
  53349. AudioEngine.prototype._unlockiOSaudio = function () {
  53350. var _this = this;
  53351. var unlockaudio = function () {
  53352. if (!_this.audioContext) {
  53353. return;
  53354. }
  53355. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  53356. var source = _this.audioContext.createBufferSource();
  53357. source.buffer = buffer;
  53358. source.connect(_this.audioContext.destination);
  53359. source.start(0);
  53360. setTimeout(function () {
  53361. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  53362. _this.unlocked = true;
  53363. window.removeEventListener('touchend', unlockaudio, false);
  53364. if (_this.onAudioUnlocked) {
  53365. _this.onAudioUnlocked();
  53366. }
  53367. }
  53368. }, 0);
  53369. };
  53370. window.addEventListener('touchend', unlockaudio, false);
  53371. };
  53372. AudioEngine.prototype._initializeAudioContext = function () {
  53373. try {
  53374. if (this.canUseWebAudio) {
  53375. this._audioContext = new AudioContext();
  53376. // create a global volume gain node
  53377. this.masterGain = this._audioContext.createGain();
  53378. this.masterGain.gain.value = 1;
  53379. this.masterGain.connect(this._audioContext.destination);
  53380. this._audioContextInitialized = true;
  53381. }
  53382. }
  53383. catch (e) {
  53384. this.canUseWebAudio = false;
  53385. BABYLON.Tools.Error("Web Audio: " + e.message);
  53386. }
  53387. };
  53388. AudioEngine.prototype.dispose = function () {
  53389. if (this.canUseWebAudio && this._audioContextInitialized) {
  53390. if (this._connectedAnalyser && this._audioContext) {
  53391. this._connectedAnalyser.stopDebugCanvas();
  53392. this._connectedAnalyser.dispose();
  53393. this.masterGain.disconnect();
  53394. this.masterGain.connect(this._audioContext.destination);
  53395. this._connectedAnalyser = null;
  53396. }
  53397. this.masterGain.gain.value = 1;
  53398. }
  53399. this.WarnedWebAudioUnsupported = false;
  53400. };
  53401. AudioEngine.prototype.getGlobalVolume = function () {
  53402. if (this.canUseWebAudio && this._audioContextInitialized) {
  53403. return this.masterGain.gain.value;
  53404. }
  53405. else {
  53406. return -1;
  53407. }
  53408. };
  53409. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  53410. if (this.canUseWebAudio && this._audioContextInitialized) {
  53411. this.masterGain.gain.value = newVolume;
  53412. }
  53413. };
  53414. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  53415. if (this._connectedAnalyser) {
  53416. this._connectedAnalyser.stopDebugCanvas();
  53417. }
  53418. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  53419. this._connectedAnalyser = analyser;
  53420. this.masterGain.disconnect();
  53421. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  53422. }
  53423. };
  53424. return AudioEngine;
  53425. }());
  53426. BABYLON.AudioEngine = AudioEngine;
  53427. })(BABYLON || (BABYLON = {}));
  53428. //# sourceMappingURL=babylon.audioEngine.js.map
  53429. var BABYLON;
  53430. (function (BABYLON) {
  53431. var Sound = /** @class */ (function () {
  53432. /**
  53433. * Create a sound and attach it to a scene
  53434. * @param name Name of your sound
  53435. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  53436. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  53437. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53438. */
  53439. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  53440. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  53441. var _this = this;
  53442. this.autoplay = false;
  53443. this.loop = false;
  53444. this.useCustomAttenuation = false;
  53445. this.spatialSound = false;
  53446. this.refDistance = 1;
  53447. this.rolloffFactor = 1;
  53448. this.maxDistance = 100;
  53449. this.distanceModel = "linear";
  53450. this._panningModel = "equalpower";
  53451. this._playbackRate = 1;
  53452. this._streaming = false;
  53453. this._startTime = 0;
  53454. this._startOffset = 0;
  53455. this._position = BABYLON.Vector3.Zero();
  53456. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  53457. this._volume = 1;
  53458. this._isReadyToPlay = false;
  53459. this.isPlaying = false;
  53460. this.isPaused = false;
  53461. this._isDirectional = false;
  53462. // Used if you'd like to create a directional sound.
  53463. // If not set, the sound will be omnidirectional
  53464. this._coneInnerAngle = 360;
  53465. this._coneOuterAngle = 360;
  53466. this._coneOuterGain = 0;
  53467. this._isOutputConnected = false;
  53468. this._urlType = "Unknown";
  53469. this.name = name;
  53470. this._scene = scene;
  53471. this._readyToPlayCallback = readyToPlayCallback;
  53472. // Default custom attenuation function is a linear attenuation
  53473. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  53474. if (currentDistance < maxDistance) {
  53475. return currentVolume * (1 - currentDistance / maxDistance);
  53476. }
  53477. else {
  53478. return 0;
  53479. }
  53480. };
  53481. if (options) {
  53482. this.autoplay = options.autoplay || false;
  53483. this.loop = options.loop || false;
  53484. // if volume === 0, we need another way to check this option
  53485. if (options.volume !== undefined) {
  53486. this._volume = options.volume;
  53487. }
  53488. this.spatialSound = options.spatialSound || false;
  53489. this.maxDistance = options.maxDistance || 100;
  53490. this.useCustomAttenuation = options.useCustomAttenuation || false;
  53491. this.rolloffFactor = options.rolloffFactor || 1;
  53492. this.refDistance = options.refDistance || 1;
  53493. this.distanceModel = options.distanceModel || "linear";
  53494. this._playbackRate = options.playbackRate || 1;
  53495. this._streaming = options.streaming || false;
  53496. }
  53497. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53498. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  53499. this._soundGain.gain.value = this._volume;
  53500. this._inputAudioNode = this._soundGain;
  53501. this._ouputAudioNode = this._soundGain;
  53502. if (this.spatialSound) {
  53503. this._createSpatialParameters();
  53504. }
  53505. this._scene.mainSoundTrack.AddSound(this);
  53506. var validParameter = true;
  53507. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  53508. if (urlOrArrayBuffer) {
  53509. if (typeof (urlOrArrayBuffer) === "string")
  53510. this._urlType = "String";
  53511. if (Array.isArray(urlOrArrayBuffer))
  53512. this._urlType = "Array";
  53513. if (urlOrArrayBuffer instanceof ArrayBuffer)
  53514. this._urlType = "ArrayBuffer";
  53515. var urls = [];
  53516. var codecSupportedFound = false;
  53517. switch (this._urlType) {
  53518. case "ArrayBuffer":
  53519. if (urlOrArrayBuffer.byteLength > 0) {
  53520. codecSupportedFound = true;
  53521. this._soundLoaded(urlOrArrayBuffer);
  53522. }
  53523. break;
  53524. case "String":
  53525. urls.push(urlOrArrayBuffer);
  53526. case "Array":
  53527. if (urls.length === 0)
  53528. urls = urlOrArrayBuffer;
  53529. // If we found a supported format, we load it immediately and stop the loop
  53530. for (var i = 0; i < urls.length; i++) {
  53531. var url = urls[i];
  53532. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53533. codecSupportedFound = true;
  53534. }
  53535. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53536. codecSupportedFound = true;
  53537. }
  53538. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53539. codecSupportedFound = true;
  53540. }
  53541. if (url.indexOf("blob:") !== -1) {
  53542. codecSupportedFound = true;
  53543. }
  53544. if (codecSupportedFound) {
  53545. // Loading sound using XHR2
  53546. if (!this._streaming) {
  53547. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53548. }
  53549. else {
  53550. this._htmlAudioElement = new Audio(url);
  53551. this._htmlAudioElement.controls = false;
  53552. this._htmlAudioElement.loop = this.loop;
  53553. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53554. this._htmlAudioElement.preload = "auto";
  53555. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53556. _this._isReadyToPlay = true;
  53557. if (_this.autoplay) {
  53558. _this.play();
  53559. }
  53560. if (_this._readyToPlayCallback) {
  53561. _this._readyToPlayCallback();
  53562. }
  53563. });
  53564. document.body.appendChild(this._htmlAudioElement);
  53565. }
  53566. break;
  53567. }
  53568. }
  53569. break;
  53570. default:
  53571. validParameter = false;
  53572. break;
  53573. }
  53574. if (!validParameter) {
  53575. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53576. }
  53577. else {
  53578. if (!codecSupportedFound) {
  53579. this._isReadyToPlay = true;
  53580. // Simulating a ready to play event to avoid breaking code path
  53581. if (this._readyToPlayCallback) {
  53582. window.setTimeout(function () {
  53583. if (_this._readyToPlayCallback) {
  53584. _this._readyToPlayCallback();
  53585. }
  53586. }, 1000);
  53587. }
  53588. }
  53589. }
  53590. }
  53591. }
  53592. else {
  53593. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53594. this._scene.mainSoundTrack.AddSound(this);
  53595. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53596. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53597. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53598. }
  53599. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53600. if (this._readyToPlayCallback) {
  53601. window.setTimeout(function () {
  53602. if (_this._readyToPlayCallback) {
  53603. _this._readyToPlayCallback();
  53604. }
  53605. }, 1000);
  53606. }
  53607. }
  53608. }
  53609. Sound.prototype.dispose = function () {
  53610. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53611. if (this.isPlaying) {
  53612. this.stop();
  53613. }
  53614. this._isReadyToPlay = false;
  53615. if (this.soundTrackId === -1) {
  53616. this._scene.mainSoundTrack.RemoveSound(this);
  53617. }
  53618. else {
  53619. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53620. }
  53621. if (this._soundGain) {
  53622. this._soundGain.disconnect();
  53623. this._soundGain = null;
  53624. }
  53625. if (this._soundPanner) {
  53626. this._soundPanner.disconnect();
  53627. this._soundPanner = null;
  53628. }
  53629. if (this._soundSource) {
  53630. this._soundSource.disconnect();
  53631. this._soundSource = null;
  53632. }
  53633. this._audioBuffer = null;
  53634. if (this._htmlAudioElement) {
  53635. this._htmlAudioElement.pause();
  53636. this._htmlAudioElement.src = "";
  53637. document.body.removeChild(this._htmlAudioElement);
  53638. }
  53639. if (this._connectedMesh && this._registerFunc) {
  53640. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53641. this._connectedMesh = null;
  53642. }
  53643. }
  53644. };
  53645. Sound.prototype.isReady = function () {
  53646. return this._isReadyToPlay;
  53647. };
  53648. Sound.prototype._soundLoaded = function (audioData) {
  53649. var _this = this;
  53650. if (!BABYLON.Engine.audioEngine.audioContext) {
  53651. return;
  53652. }
  53653. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53654. _this._audioBuffer = buffer;
  53655. _this._isReadyToPlay = true;
  53656. if (_this.autoplay) {
  53657. _this.play();
  53658. }
  53659. if (_this._readyToPlayCallback) {
  53660. _this._readyToPlayCallback();
  53661. }
  53662. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53663. };
  53664. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53665. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53666. this._audioBuffer = audioBuffer;
  53667. this._isReadyToPlay = true;
  53668. }
  53669. };
  53670. Sound.prototype.updateOptions = function (options) {
  53671. if (options) {
  53672. this.loop = options.loop || this.loop;
  53673. this.maxDistance = options.maxDistance || this.maxDistance;
  53674. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53675. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53676. this.refDistance = options.refDistance || this.refDistance;
  53677. this.distanceModel = options.distanceModel || this.distanceModel;
  53678. this._playbackRate = options.playbackRate || this._playbackRate;
  53679. this._updateSpatialParameters();
  53680. if (this.isPlaying) {
  53681. if (this._streaming) {
  53682. this._htmlAudioElement.playbackRate = this._playbackRate;
  53683. }
  53684. else {
  53685. if (this._soundSource) {
  53686. this._soundSource.playbackRate.value = this._playbackRate;
  53687. }
  53688. }
  53689. }
  53690. }
  53691. };
  53692. Sound.prototype._createSpatialParameters = function () {
  53693. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53694. if (this._scene.headphone) {
  53695. this._panningModel = "HRTF";
  53696. }
  53697. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53698. this._updateSpatialParameters();
  53699. this._soundPanner.connect(this._ouputAudioNode);
  53700. this._inputAudioNode = this._soundPanner;
  53701. }
  53702. };
  53703. Sound.prototype._updateSpatialParameters = function () {
  53704. if (this.spatialSound && this._soundPanner) {
  53705. if (this.useCustomAttenuation) {
  53706. // Tricks to disable in a way embedded Web Audio attenuation
  53707. this._soundPanner.distanceModel = "linear";
  53708. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53709. this._soundPanner.refDistance = 1;
  53710. this._soundPanner.rolloffFactor = 1;
  53711. this._soundPanner.panningModel = this._panningModel;
  53712. }
  53713. else {
  53714. this._soundPanner.distanceModel = this.distanceModel;
  53715. this._soundPanner.maxDistance = this.maxDistance;
  53716. this._soundPanner.refDistance = this.refDistance;
  53717. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53718. this._soundPanner.panningModel = this._panningModel;
  53719. }
  53720. }
  53721. };
  53722. Sound.prototype.switchPanningModelToHRTF = function () {
  53723. this._panningModel = "HRTF";
  53724. this._switchPanningModel();
  53725. };
  53726. Sound.prototype.switchPanningModelToEqualPower = function () {
  53727. this._panningModel = "equalpower";
  53728. this._switchPanningModel();
  53729. };
  53730. Sound.prototype._switchPanningModel = function () {
  53731. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53732. this._soundPanner.panningModel = this._panningModel;
  53733. }
  53734. };
  53735. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53736. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53737. if (this._isOutputConnected) {
  53738. this._ouputAudioNode.disconnect();
  53739. }
  53740. this._ouputAudioNode.connect(soundTrackAudioNode);
  53741. this._isOutputConnected = true;
  53742. }
  53743. };
  53744. /**
  53745. * Transform this sound into a directional source
  53746. * @param coneInnerAngle Size of the inner cone in degree
  53747. * @param coneOuterAngle Size of the outer cone in degree
  53748. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53749. */
  53750. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53751. if (coneOuterAngle < coneInnerAngle) {
  53752. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53753. return;
  53754. }
  53755. this._coneInnerAngle = coneInnerAngle;
  53756. this._coneOuterAngle = coneOuterAngle;
  53757. this._coneOuterGain = coneOuterGain;
  53758. this._isDirectional = true;
  53759. if (this.isPlaying && this.loop) {
  53760. this.stop();
  53761. this.play();
  53762. }
  53763. };
  53764. Sound.prototype.setPosition = function (newPosition) {
  53765. this._position = newPosition;
  53766. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53767. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53768. }
  53769. };
  53770. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53771. this._localDirection = newLocalDirection;
  53772. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53773. this._updateDirection();
  53774. }
  53775. };
  53776. Sound.prototype._updateDirection = function () {
  53777. if (!this._connectedMesh || !this._soundPanner) {
  53778. return;
  53779. }
  53780. var mat = this._connectedMesh.getWorldMatrix();
  53781. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53782. direction.normalize();
  53783. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53784. };
  53785. Sound.prototype.updateDistanceFromListener = function () {
  53786. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53787. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53788. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53789. }
  53790. };
  53791. Sound.prototype.setAttenuationFunction = function (callback) {
  53792. this._customAttenuationFunction = callback;
  53793. };
  53794. /**
  53795. * Play the sound
  53796. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53797. * @param offset (optional) Start the sound setting it at a specific time
  53798. */
  53799. Sound.prototype.play = function (time, offset) {
  53800. var _this = this;
  53801. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53802. try {
  53803. if (this._startOffset < 0) {
  53804. time = -this._startOffset;
  53805. this._startOffset = 0;
  53806. }
  53807. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53808. if (!this._soundSource || !this._streamingSource) {
  53809. if (this.spatialSound && this._soundPanner) {
  53810. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53811. if (this._isDirectional) {
  53812. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53813. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53814. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53815. if (this._connectedMesh) {
  53816. this._updateDirection();
  53817. }
  53818. else {
  53819. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53820. }
  53821. }
  53822. }
  53823. }
  53824. if (this._streaming) {
  53825. if (!this._streamingSource) {
  53826. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53827. this._htmlAudioElement.onended = function () { _this._onended(); };
  53828. this._htmlAudioElement.playbackRate = this._playbackRate;
  53829. }
  53830. this._streamingSource.disconnect();
  53831. this._streamingSource.connect(this._inputAudioNode);
  53832. this._htmlAudioElement.play();
  53833. }
  53834. else {
  53835. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53836. this._soundSource.buffer = this._audioBuffer;
  53837. this._soundSource.connect(this._inputAudioNode);
  53838. this._soundSource.loop = this.loop;
  53839. this._soundSource.playbackRate.value = this._playbackRate;
  53840. this._soundSource.onended = function () { _this._onended(); };
  53841. if (this._soundSource.buffer) {
  53842. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53843. }
  53844. }
  53845. this._startTime = startTime;
  53846. this.isPlaying = true;
  53847. this.isPaused = false;
  53848. }
  53849. catch (ex) {
  53850. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53851. }
  53852. }
  53853. };
  53854. Sound.prototype._onended = function () {
  53855. this.isPlaying = false;
  53856. if (this.onended) {
  53857. this.onended();
  53858. }
  53859. };
  53860. /**
  53861. * Stop the sound
  53862. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53863. */
  53864. Sound.prototype.stop = function (time) {
  53865. if (this.isPlaying) {
  53866. if (this._streaming) {
  53867. this._htmlAudioElement.pause();
  53868. // Test needed for Firefox or it will generate an Invalid State Error
  53869. if (this._htmlAudioElement.currentTime > 0) {
  53870. this._htmlAudioElement.currentTime = 0;
  53871. }
  53872. }
  53873. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53874. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53875. this._soundSource.stop(stopTime);
  53876. this._soundSource.onended = function () { };
  53877. if (!this.isPaused) {
  53878. this._startOffset = 0;
  53879. }
  53880. }
  53881. this.isPlaying = false;
  53882. }
  53883. };
  53884. Sound.prototype.pause = function () {
  53885. if (this.isPlaying) {
  53886. this.isPaused = true;
  53887. if (this._streaming) {
  53888. this._htmlAudioElement.pause();
  53889. }
  53890. else if (BABYLON.Engine.audioEngine.audioContext) {
  53891. this.stop(0);
  53892. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53893. }
  53894. }
  53895. };
  53896. Sound.prototype.setVolume = function (newVolume, time) {
  53897. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53898. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53899. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53900. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53901. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53902. }
  53903. else {
  53904. this._soundGain.gain.value = newVolume;
  53905. }
  53906. }
  53907. this._volume = newVolume;
  53908. };
  53909. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53910. this._playbackRate = newPlaybackRate;
  53911. if (this.isPlaying) {
  53912. if (this._streaming) {
  53913. this._htmlAudioElement.playbackRate = this._playbackRate;
  53914. }
  53915. else if (this._soundSource) {
  53916. this._soundSource.playbackRate.value = this._playbackRate;
  53917. }
  53918. }
  53919. };
  53920. Sound.prototype.getVolume = function () {
  53921. return this._volume;
  53922. };
  53923. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53924. var _this = this;
  53925. if (this._connectedMesh && this._registerFunc) {
  53926. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53927. this._registerFunc = null;
  53928. }
  53929. this._connectedMesh = meshToConnectTo;
  53930. if (!this.spatialSound) {
  53931. this.spatialSound = true;
  53932. this._createSpatialParameters();
  53933. if (this.isPlaying && this.loop) {
  53934. this.stop();
  53935. this.play();
  53936. }
  53937. }
  53938. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53939. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53940. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53941. };
  53942. Sound.prototype.detachFromMesh = function () {
  53943. if (this._connectedMesh && this._registerFunc) {
  53944. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53945. this._registerFunc = null;
  53946. this._connectedMesh = null;
  53947. }
  53948. };
  53949. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53950. if (!node.getBoundingInfo) {
  53951. return;
  53952. }
  53953. var mesh = node;
  53954. var boundingInfo = mesh.getBoundingInfo();
  53955. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53956. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53957. this._updateDirection();
  53958. }
  53959. };
  53960. Sound.prototype.clone = function () {
  53961. var _this = this;
  53962. if (!this._streaming) {
  53963. var setBufferAndRun = function () {
  53964. if (_this._isReadyToPlay) {
  53965. clonedSound._audioBuffer = _this.getAudioBuffer();
  53966. clonedSound._isReadyToPlay = true;
  53967. if (clonedSound.autoplay) {
  53968. clonedSound.play();
  53969. }
  53970. }
  53971. else {
  53972. window.setTimeout(setBufferAndRun, 300);
  53973. }
  53974. };
  53975. var currentOptions = {
  53976. autoplay: this.autoplay, loop: this.loop,
  53977. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53978. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53979. refDistance: this.refDistance, distanceModel: this.distanceModel
  53980. };
  53981. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53982. if (this.useCustomAttenuation) {
  53983. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53984. }
  53985. clonedSound.setPosition(this._position);
  53986. clonedSound.setPlaybackRate(this._playbackRate);
  53987. setBufferAndRun();
  53988. return clonedSound;
  53989. }
  53990. else {
  53991. return null;
  53992. }
  53993. };
  53994. Sound.prototype.getAudioBuffer = function () {
  53995. return this._audioBuffer;
  53996. };
  53997. Sound.prototype.serialize = function () {
  53998. var serializationObject = {
  53999. name: this.name,
  54000. url: this.name,
  54001. autoplay: this.autoplay,
  54002. loop: this.loop,
  54003. volume: this._volume,
  54004. spatialSound: this.spatialSound,
  54005. maxDistance: this.maxDistance,
  54006. rolloffFactor: this.rolloffFactor,
  54007. refDistance: this.refDistance,
  54008. distanceModel: this.distanceModel,
  54009. playbackRate: this._playbackRate,
  54010. panningModel: this._panningModel,
  54011. soundTrackId: this.soundTrackId
  54012. };
  54013. if (this.spatialSound) {
  54014. if (this._connectedMesh)
  54015. serializationObject.connectedMeshId = this._connectedMesh.id;
  54016. serializationObject.position = this._position.asArray();
  54017. serializationObject.refDistance = this.refDistance;
  54018. serializationObject.distanceModel = this.distanceModel;
  54019. serializationObject.isDirectional = this._isDirectional;
  54020. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  54021. serializationObject.coneInnerAngle = this._coneInnerAngle;
  54022. serializationObject.coneOuterAngle = this._coneOuterAngle;
  54023. serializationObject.coneOuterGain = this._coneOuterGain;
  54024. }
  54025. return serializationObject;
  54026. };
  54027. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  54028. var soundName = parsedSound.name;
  54029. var soundUrl;
  54030. if (parsedSound.url) {
  54031. soundUrl = rootUrl + parsedSound.url;
  54032. }
  54033. else {
  54034. soundUrl = rootUrl + soundName;
  54035. }
  54036. var options = {
  54037. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  54038. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  54039. rolloffFactor: parsedSound.rolloffFactor,
  54040. refDistance: parsedSound.refDistance,
  54041. distanceModel: parsedSound.distanceModel,
  54042. playbackRate: parsedSound.playbackRate
  54043. };
  54044. var newSound;
  54045. if (!sourceSound) {
  54046. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  54047. scene._addPendingData(newSound);
  54048. }
  54049. else {
  54050. var setBufferAndRun = function () {
  54051. if (sourceSound._isReadyToPlay) {
  54052. newSound._audioBuffer = sourceSound.getAudioBuffer();
  54053. newSound._isReadyToPlay = true;
  54054. if (newSound.autoplay) {
  54055. newSound.play();
  54056. }
  54057. }
  54058. else {
  54059. window.setTimeout(setBufferAndRun, 300);
  54060. }
  54061. };
  54062. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  54063. setBufferAndRun();
  54064. }
  54065. if (parsedSound.position) {
  54066. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  54067. newSound.setPosition(soundPosition);
  54068. }
  54069. if (parsedSound.isDirectional) {
  54070. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  54071. if (parsedSound.localDirectionToMesh) {
  54072. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  54073. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  54074. }
  54075. }
  54076. if (parsedSound.connectedMeshId) {
  54077. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  54078. if (connectedMesh) {
  54079. newSound.attachToMesh(connectedMesh);
  54080. }
  54081. }
  54082. return newSound;
  54083. };
  54084. return Sound;
  54085. }());
  54086. BABYLON.Sound = Sound;
  54087. })(BABYLON || (BABYLON = {}));
  54088. //# sourceMappingURL=babylon.sound.js.map
  54089. var BABYLON;
  54090. (function (BABYLON) {
  54091. var SoundTrack = /** @class */ (function () {
  54092. function SoundTrack(scene, options) {
  54093. this.id = -1;
  54094. this._isMainTrack = false;
  54095. this._isInitialized = false;
  54096. this._scene = scene;
  54097. this.soundCollection = new Array();
  54098. this._options = options;
  54099. if (!this._isMainTrack) {
  54100. this._scene.soundTracks.push(this);
  54101. this.id = this._scene.soundTracks.length - 1;
  54102. }
  54103. }
  54104. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  54105. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54106. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  54107. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  54108. if (this._options) {
  54109. if (this._options.volume) {
  54110. this._outputAudioNode.gain.value = this._options.volume;
  54111. }
  54112. if (this._options.mainTrack) {
  54113. this._isMainTrack = this._options.mainTrack;
  54114. }
  54115. }
  54116. this._isInitialized = true;
  54117. }
  54118. };
  54119. SoundTrack.prototype.dispose = function () {
  54120. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54121. if (this._connectedAnalyser) {
  54122. this._connectedAnalyser.stopDebugCanvas();
  54123. }
  54124. while (this.soundCollection.length) {
  54125. this.soundCollection[0].dispose();
  54126. }
  54127. if (this._outputAudioNode) {
  54128. this._outputAudioNode.disconnect();
  54129. }
  54130. this._outputAudioNode = null;
  54131. }
  54132. };
  54133. SoundTrack.prototype.AddSound = function (sound) {
  54134. if (!this._isInitialized) {
  54135. this._initializeSoundTrackAudioGraph();
  54136. }
  54137. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54138. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  54139. }
  54140. if (sound.soundTrackId) {
  54141. if (sound.soundTrackId === -1) {
  54142. this._scene.mainSoundTrack.RemoveSound(sound);
  54143. }
  54144. else {
  54145. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  54146. }
  54147. }
  54148. this.soundCollection.push(sound);
  54149. sound.soundTrackId = this.id;
  54150. };
  54151. SoundTrack.prototype.RemoveSound = function (sound) {
  54152. var index = this.soundCollection.indexOf(sound);
  54153. if (index !== -1) {
  54154. this.soundCollection.splice(index, 1);
  54155. }
  54156. };
  54157. SoundTrack.prototype.setVolume = function (newVolume) {
  54158. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54159. this._outputAudioNode.gain.value = newVolume;
  54160. }
  54161. };
  54162. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  54163. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54164. for (var i = 0; i < this.soundCollection.length; i++) {
  54165. this.soundCollection[i].switchPanningModelToHRTF();
  54166. }
  54167. }
  54168. };
  54169. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  54170. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54171. for (var i = 0; i < this.soundCollection.length; i++) {
  54172. this.soundCollection[i].switchPanningModelToEqualPower();
  54173. }
  54174. }
  54175. };
  54176. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  54177. if (this._connectedAnalyser) {
  54178. this._connectedAnalyser.stopDebugCanvas();
  54179. }
  54180. this._connectedAnalyser = analyser;
  54181. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54182. this._outputAudioNode.disconnect();
  54183. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  54184. }
  54185. };
  54186. return SoundTrack;
  54187. }());
  54188. BABYLON.SoundTrack = SoundTrack;
  54189. })(BABYLON || (BABYLON = {}));
  54190. //# sourceMappingURL=babylon.soundtrack.js.map
  54191. var BABYLON;
  54192. (function (BABYLON) {
  54193. var Analyser = /** @class */ (function () {
  54194. function Analyser(scene) {
  54195. this.SMOOTHING = 0.75;
  54196. this.FFT_SIZE = 512;
  54197. this.BARGRAPHAMPLITUDE = 256;
  54198. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54199. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54200. this._scene = scene;
  54201. this._audioEngine = BABYLON.Engine.audioEngine;
  54202. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  54203. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54204. this._webAudioAnalyser.minDecibels = -140;
  54205. this._webAudioAnalyser.maxDecibels = 0;
  54206. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54207. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54208. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54209. }
  54210. }
  54211. Analyser.prototype.getFrequencyBinCount = function () {
  54212. if (this._audioEngine.canUseWebAudio) {
  54213. return this._webAudioAnalyser.frequencyBinCount;
  54214. }
  54215. else {
  54216. return 0;
  54217. }
  54218. };
  54219. Analyser.prototype.getByteFrequencyData = function () {
  54220. if (this._audioEngine.canUseWebAudio) {
  54221. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54222. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54223. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54224. }
  54225. return this._byteFreqs;
  54226. };
  54227. Analyser.prototype.getByteTimeDomainData = function () {
  54228. if (this._audioEngine.canUseWebAudio) {
  54229. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54230. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54231. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54232. }
  54233. return this._byteTime;
  54234. };
  54235. Analyser.prototype.getFloatFrequencyData = function () {
  54236. if (this._audioEngine.canUseWebAudio) {
  54237. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54238. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54239. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54240. }
  54241. return this._floatFreqs;
  54242. };
  54243. Analyser.prototype.drawDebugCanvas = function () {
  54244. var _this = this;
  54245. if (this._audioEngine.canUseWebAudio) {
  54246. if (!this._debugCanvas) {
  54247. this._debugCanvas = document.createElement("canvas");
  54248. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54249. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54250. this._debugCanvas.style.position = "absolute";
  54251. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54252. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54253. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54254. document.body.appendChild(this._debugCanvas);
  54255. this._registerFunc = function () {
  54256. _this.drawDebugCanvas();
  54257. };
  54258. this._scene.registerBeforeRender(this._registerFunc);
  54259. }
  54260. if (this._registerFunc && this._debugCanvasContext) {
  54261. var workingArray = this.getByteFrequencyData();
  54262. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54263. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54264. // Draw the frequency domain chart.
  54265. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54266. var value = workingArray[i];
  54267. var percent = value / this.BARGRAPHAMPLITUDE;
  54268. var height = this.DEBUGCANVASSIZE.height * percent;
  54269. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54270. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54271. var hue = i / this.getFrequencyBinCount() * 360;
  54272. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54273. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54274. }
  54275. }
  54276. }
  54277. };
  54278. Analyser.prototype.stopDebugCanvas = function () {
  54279. if (this._debugCanvas) {
  54280. if (this._registerFunc) {
  54281. this._scene.unregisterBeforeRender(this._registerFunc);
  54282. this._registerFunc = null;
  54283. }
  54284. document.body.removeChild(this._debugCanvas);
  54285. this._debugCanvas = null;
  54286. this._debugCanvasContext = null;
  54287. }
  54288. };
  54289. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54290. if (this._audioEngine.canUseWebAudio) {
  54291. inputAudioNode.connect(this._webAudioAnalyser);
  54292. this._webAudioAnalyser.connect(outputAudioNode);
  54293. }
  54294. };
  54295. Analyser.prototype.dispose = function () {
  54296. if (this._audioEngine.canUseWebAudio) {
  54297. this._webAudioAnalyser.disconnect();
  54298. }
  54299. };
  54300. return Analyser;
  54301. }());
  54302. BABYLON.Analyser = Analyser;
  54303. })(BABYLON || (BABYLON = {}));
  54304. //# sourceMappingURL=babylon.analyser.js.map
  54305. var BABYLON;
  54306. (function (BABYLON) {
  54307. var CubeTexture = /** @class */ (function (_super) {
  54308. __extends(CubeTexture, _super);
  54309. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  54310. if (extensions === void 0) { extensions = null; }
  54311. if (noMipmap === void 0) { noMipmap = false; }
  54312. if (files === void 0) { files = null; }
  54313. if (onLoad === void 0) { onLoad = null; }
  54314. if (onError === void 0) { onError = null; }
  54315. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54316. if (prefiltered === void 0) { prefiltered = false; }
  54317. if (forcedExtension === void 0) { forcedExtension = null; }
  54318. var _this = _super.call(this, scene) || this;
  54319. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54320. _this.name = rootUrl;
  54321. _this.url = rootUrl;
  54322. _this._noMipmap = noMipmap;
  54323. _this.hasAlpha = false;
  54324. _this._format = format;
  54325. _this._prefiltered = prefiltered;
  54326. _this.isCube = true;
  54327. _this._textureMatrix = BABYLON.Matrix.Identity();
  54328. if (prefiltered) {
  54329. _this.gammaSpace = false;
  54330. }
  54331. if (!rootUrl && !files) {
  54332. return _this;
  54333. }
  54334. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  54335. var lastDot = rootUrl.lastIndexOf(".");
  54336. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  54337. var isDDS = (extension === ".dds");
  54338. if (!files) {
  54339. if (!isDDS && !extensions) {
  54340. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  54341. }
  54342. files = [];
  54343. if (extensions) {
  54344. for (var index = 0; index < extensions.length; index++) {
  54345. files.push(rootUrl + extensions[index]);
  54346. }
  54347. }
  54348. }
  54349. _this._files = files;
  54350. if (!_this._texture) {
  54351. if (!scene.useDelayedTextureLoading) {
  54352. if (prefiltered) {
  54353. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  54354. }
  54355. else {
  54356. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  54357. }
  54358. }
  54359. else {
  54360. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54361. }
  54362. }
  54363. else if (onLoad) {
  54364. if (_this._texture.isReady) {
  54365. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  54366. }
  54367. else {
  54368. _this._texture.onLoadedObservable.add(onLoad);
  54369. }
  54370. }
  54371. return _this;
  54372. }
  54373. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  54374. return new CubeTexture("", scene, null, noMipmap, files);
  54375. };
  54376. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  54377. if (forcedExtension === void 0) { forcedExtension = null; }
  54378. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  54379. };
  54380. // Methods
  54381. CubeTexture.prototype.delayLoad = function () {
  54382. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54383. return;
  54384. }
  54385. var scene = this.getScene();
  54386. if (!scene) {
  54387. return;
  54388. }
  54389. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54390. this._texture = this._getFromCache(this.url, this._noMipmap);
  54391. if (!this._texture) {
  54392. if (this._prefiltered) {
  54393. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  54394. }
  54395. else {
  54396. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  54397. }
  54398. }
  54399. };
  54400. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  54401. return this._textureMatrix;
  54402. };
  54403. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  54404. this._textureMatrix = value;
  54405. };
  54406. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54407. var texture = BABYLON.SerializationHelper.Parse(function () {
  54408. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  54409. }, parsedTexture, scene);
  54410. // Animations
  54411. if (parsedTexture.animations) {
  54412. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  54413. var parsedAnimation = parsedTexture.animations[animationIndex];
  54414. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54415. }
  54416. }
  54417. return texture;
  54418. };
  54419. CubeTexture.prototype.clone = function () {
  54420. var _this = this;
  54421. return BABYLON.SerializationHelper.Clone(function () {
  54422. var scene = _this.getScene();
  54423. if (!scene) {
  54424. return _this;
  54425. }
  54426. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  54427. }, this);
  54428. };
  54429. return CubeTexture;
  54430. }(BABYLON.BaseTexture));
  54431. BABYLON.CubeTexture = CubeTexture;
  54432. })(BABYLON || (BABYLON = {}));
  54433. //# sourceMappingURL=babylon.cubeTexture.js.map
  54434. var BABYLON;
  54435. (function (BABYLON) {
  54436. var RenderTargetTexture = /** @class */ (function (_super) {
  54437. __extends(RenderTargetTexture, _super);
  54438. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  54439. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  54440. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54441. if (isCube === void 0) { isCube = false; }
  54442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54443. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54444. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  54445. if (isMulti === void 0) { isMulti = false; }
  54446. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54447. _this.isCube = isCube;
  54448. /**
  54449. * Use this list to define the list of mesh you want to render.
  54450. */
  54451. _this.renderList = new Array();
  54452. _this.renderParticles = true;
  54453. _this.renderSprites = false;
  54454. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  54455. _this.ignoreCameraViewport = false;
  54456. // Events
  54457. /**
  54458. * An event triggered when the texture is unbind.
  54459. * @type {BABYLON.Observable}
  54460. */
  54461. _this.onBeforeBindObservable = new BABYLON.Observable();
  54462. /**
  54463. * An event triggered when the texture is unbind.
  54464. * @type {BABYLON.Observable}
  54465. */
  54466. _this.onAfterUnbindObservable = new BABYLON.Observable();
  54467. /**
  54468. * An event triggered before rendering the texture
  54469. * @type {BABYLON.Observable}
  54470. */
  54471. _this.onBeforeRenderObservable = new BABYLON.Observable();
  54472. /**
  54473. * An event triggered after rendering the texture
  54474. * @type {BABYLON.Observable}
  54475. */
  54476. _this.onAfterRenderObservable = new BABYLON.Observable();
  54477. /**
  54478. * An event triggered after the texture clear
  54479. * @type {BABYLON.Observable}
  54480. */
  54481. _this.onClearObservable = new BABYLON.Observable();
  54482. _this._currentRefreshId = -1;
  54483. _this._refreshRate = 1;
  54484. _this._samples = 1;
  54485. scene = _this.getScene();
  54486. if (!scene) {
  54487. return _this;
  54488. }
  54489. _this._engine = scene.getEngine();
  54490. _this.name = name;
  54491. _this.isRenderTarget = true;
  54492. _this._initialSizeParameter = size;
  54493. _this._processSizeParameter(size);
  54494. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  54495. });
  54496. _this._generateMipMaps = generateMipMaps ? true : false;
  54497. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  54498. // Rendering groups
  54499. _this._renderingManager = new BABYLON.RenderingManager(scene);
  54500. if (isMulti) {
  54501. return _this;
  54502. }
  54503. _this._renderTargetOptions = {
  54504. generateMipMaps: generateMipMaps,
  54505. type: type,
  54506. samplingMode: samplingMode,
  54507. generateDepthBuffer: generateDepthBuffer,
  54508. generateStencilBuffer: generateStencilBuffer
  54509. };
  54510. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  54511. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54512. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54513. }
  54514. if (isCube) {
  54515. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  54516. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  54517. _this._textureMatrix = BABYLON.Matrix.Identity();
  54518. }
  54519. else {
  54520. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  54521. }
  54522. return _this;
  54523. }
  54524. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  54525. get: function () {
  54526. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  54527. },
  54528. enumerable: true,
  54529. configurable: true
  54530. });
  54531. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54532. get: function () {
  54533. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54534. },
  54535. enumerable: true,
  54536. configurable: true
  54537. });
  54538. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54539. get: function () {
  54540. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54541. },
  54542. enumerable: true,
  54543. configurable: true
  54544. });
  54545. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54546. set: function (callback) {
  54547. if (this._onAfterUnbindObserver) {
  54548. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54549. }
  54550. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54551. },
  54552. enumerable: true,
  54553. configurable: true
  54554. });
  54555. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54556. set: function (callback) {
  54557. if (this._onBeforeRenderObserver) {
  54558. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54559. }
  54560. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54561. },
  54562. enumerable: true,
  54563. configurable: true
  54564. });
  54565. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54566. set: function (callback) {
  54567. if (this._onAfterRenderObserver) {
  54568. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54569. }
  54570. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54571. },
  54572. enumerable: true,
  54573. configurable: true
  54574. });
  54575. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54576. set: function (callback) {
  54577. if (this._onClearObserver) {
  54578. this.onClearObservable.remove(this._onClearObserver);
  54579. }
  54580. this._onClearObserver = this.onClearObservable.add(callback);
  54581. },
  54582. enumerable: true,
  54583. configurable: true
  54584. });
  54585. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54586. get: function () {
  54587. return this._renderTargetOptions;
  54588. },
  54589. enumerable: true,
  54590. configurable: true
  54591. });
  54592. RenderTargetTexture.prototype._onRatioRescale = function () {
  54593. if (this._sizeRatio) {
  54594. this.resize(this._initialSizeParameter);
  54595. }
  54596. };
  54597. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54598. if (size.ratio) {
  54599. this._sizeRatio = size.ratio;
  54600. this._size = {
  54601. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54602. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54603. };
  54604. }
  54605. else {
  54606. this._size = size;
  54607. }
  54608. };
  54609. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54610. get: function () {
  54611. return this._samples;
  54612. },
  54613. set: function (value) {
  54614. if (this._samples === value) {
  54615. return;
  54616. }
  54617. var scene = this.getScene();
  54618. if (!scene) {
  54619. return;
  54620. }
  54621. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54622. },
  54623. enumerable: true,
  54624. configurable: true
  54625. });
  54626. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54627. this._currentRefreshId = -1;
  54628. };
  54629. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54630. get: function () {
  54631. return this._refreshRate;
  54632. },
  54633. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54634. set: function (value) {
  54635. this._refreshRate = value;
  54636. this.resetRefreshCounter();
  54637. },
  54638. enumerable: true,
  54639. configurable: true
  54640. });
  54641. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54642. if (!this._postProcessManager) {
  54643. var scene = this.getScene();
  54644. if (!scene) {
  54645. return;
  54646. }
  54647. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54648. this._postProcesses = new Array();
  54649. }
  54650. this._postProcesses.push(postProcess);
  54651. this._postProcesses[0].autoClear = false;
  54652. };
  54653. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54654. if (!this._postProcesses) {
  54655. return;
  54656. }
  54657. if (dispose) {
  54658. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54659. var postProcess = _a[_i];
  54660. postProcess.dispose();
  54661. }
  54662. }
  54663. this._postProcesses = [];
  54664. };
  54665. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54666. if (!this._postProcesses) {
  54667. return;
  54668. }
  54669. var index = this._postProcesses.indexOf(postProcess);
  54670. if (index === -1) {
  54671. return;
  54672. }
  54673. this._postProcesses.splice(index, 1);
  54674. if (this._postProcesses.length > 0) {
  54675. this._postProcesses[0].autoClear = false;
  54676. }
  54677. };
  54678. RenderTargetTexture.prototype._shouldRender = function () {
  54679. if (this._currentRefreshId === -1) {
  54680. this._currentRefreshId = 1;
  54681. return true;
  54682. }
  54683. if (this.refreshRate === this._currentRefreshId) {
  54684. this._currentRefreshId = 1;
  54685. return true;
  54686. }
  54687. this._currentRefreshId++;
  54688. return false;
  54689. };
  54690. RenderTargetTexture.prototype.getRenderSize = function () {
  54691. if (this._size.width) {
  54692. return this._size.width;
  54693. }
  54694. return this._size;
  54695. };
  54696. RenderTargetTexture.prototype.getRenderWidth = function () {
  54697. if (this._size.width) {
  54698. return this._size.width;
  54699. }
  54700. return this._size;
  54701. };
  54702. RenderTargetTexture.prototype.getRenderHeight = function () {
  54703. if (this._size.width) {
  54704. return this._size.height;
  54705. }
  54706. return this._size;
  54707. };
  54708. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54709. get: function () {
  54710. return true;
  54711. },
  54712. enumerable: true,
  54713. configurable: true
  54714. });
  54715. RenderTargetTexture.prototype.scale = function (ratio) {
  54716. var newSize = this.getRenderSize() * ratio;
  54717. this.resize(newSize);
  54718. };
  54719. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54720. if (this.isCube) {
  54721. return this._textureMatrix;
  54722. }
  54723. return _super.prototype.getReflectionTextureMatrix.call(this);
  54724. };
  54725. RenderTargetTexture.prototype.resize = function (size) {
  54726. this.releaseInternalTexture();
  54727. var scene = this.getScene();
  54728. if (!scene) {
  54729. return;
  54730. }
  54731. this._processSizeParameter(size);
  54732. if (this.isCube) {
  54733. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54734. }
  54735. else {
  54736. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54737. }
  54738. };
  54739. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54740. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54741. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54742. var scene = this.getScene();
  54743. if (!scene) {
  54744. return;
  54745. }
  54746. var engine = scene.getEngine();
  54747. if (this.useCameraPostProcesses !== undefined) {
  54748. useCameraPostProcess = this.useCameraPostProcesses;
  54749. }
  54750. if (this._waitingRenderList) {
  54751. this.renderList = [];
  54752. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54753. var id = this._waitingRenderList[index];
  54754. var mesh_1 = scene.getMeshByID(id);
  54755. if (mesh_1) {
  54756. this.renderList.push(mesh_1);
  54757. }
  54758. }
  54759. delete this._waitingRenderList;
  54760. }
  54761. // Is predicate defined?
  54762. if (this.renderListPredicate) {
  54763. if (this.renderList) {
  54764. this.renderList.splice(0); // Clear previous renderList
  54765. }
  54766. else {
  54767. this.renderList = [];
  54768. }
  54769. var scene = this.getScene();
  54770. if (!scene) {
  54771. return;
  54772. }
  54773. var sceneMeshes = scene.meshes;
  54774. for (var index = 0; index < sceneMeshes.length; index++) {
  54775. var mesh = sceneMeshes[index];
  54776. if (this.renderListPredicate(mesh)) {
  54777. this.renderList.push(mesh);
  54778. }
  54779. }
  54780. }
  54781. this.onBeforeBindObservable.notifyObservers(this);
  54782. // Set custom projection.
  54783. // Needs to be before binding to prevent changing the aspect ratio.
  54784. var camera;
  54785. if (this.activeCamera) {
  54786. camera = this.activeCamera;
  54787. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54788. if (this.activeCamera !== scene.activeCamera) {
  54789. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54790. }
  54791. }
  54792. else {
  54793. camera = scene.activeCamera;
  54794. if (camera) {
  54795. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54796. }
  54797. }
  54798. // Prepare renderingManager
  54799. this._renderingManager.reset();
  54800. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54801. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54802. var sceneRenderId = scene.getRenderId();
  54803. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54804. var mesh = currentRenderList[meshIndex];
  54805. if (mesh) {
  54806. if (!mesh.isReady()) {
  54807. // Reset _currentRefreshId
  54808. this.resetRefreshCounter();
  54809. continue;
  54810. }
  54811. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54812. var isMasked = void 0;
  54813. if (!this.renderList && camera) {
  54814. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54815. }
  54816. else {
  54817. isMasked = false;
  54818. }
  54819. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54820. mesh._activate(sceneRenderId);
  54821. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54822. var subMesh = mesh.subMeshes[subIndex];
  54823. scene._activeIndices.addCount(subMesh.indexCount, false);
  54824. this._renderingManager.dispatch(subMesh, mesh);
  54825. }
  54826. }
  54827. }
  54828. }
  54829. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54830. var particleSystem = scene.particleSystems[particleIndex];
  54831. var emitter = particleSystem.emitter;
  54832. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54833. continue;
  54834. }
  54835. if (currentRenderList.indexOf(emitter) >= 0) {
  54836. this._renderingManager.dispatchParticles(particleSystem);
  54837. }
  54838. }
  54839. if (this.isCube) {
  54840. for (var face = 0; face < 6; face++) {
  54841. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54842. scene.incrementRenderId();
  54843. scene.resetCachedMaterial();
  54844. }
  54845. }
  54846. else {
  54847. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54848. }
  54849. this.onAfterUnbindObservable.notifyObservers(this);
  54850. if (scene.activeCamera) {
  54851. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54852. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54853. }
  54854. engine.setViewport(scene.activeCamera.viewport);
  54855. }
  54856. scene.resetCachedMaterial();
  54857. };
  54858. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54859. var minimum = 128;
  54860. var x = renderDimension * scale;
  54861. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54862. // Ensure we don't exceed the render dimension (while staying POT)
  54863. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54864. };
  54865. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54866. var _this = this;
  54867. if (!this._texture) {
  54868. return;
  54869. }
  54870. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54871. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54872. });
  54873. };
  54874. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54875. var scene = this.getScene();
  54876. if (!scene) {
  54877. return;
  54878. }
  54879. var engine = scene.getEngine();
  54880. if (!this._texture) {
  54881. return;
  54882. }
  54883. // Bind
  54884. if (this._postProcessManager) {
  54885. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54886. }
  54887. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54888. if (this._texture) {
  54889. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54890. }
  54891. }
  54892. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54893. // Clear
  54894. if (this.onClearObservable.hasObservers()) {
  54895. this.onClearObservable.notifyObservers(engine);
  54896. }
  54897. else {
  54898. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54899. }
  54900. if (!this._doNotChangeAspectRatio) {
  54901. scene.updateTransformMatrix(true);
  54902. }
  54903. // Render
  54904. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54905. if (this._postProcessManager) {
  54906. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54907. }
  54908. else if (useCameraPostProcess) {
  54909. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54910. }
  54911. if (!this._doNotChangeAspectRatio) {
  54912. scene.updateTransformMatrix(true);
  54913. }
  54914. // Dump ?
  54915. if (dumpForDebug) {
  54916. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54917. }
  54918. // Unbind
  54919. if (!this.isCube || faceIndex === 5) {
  54920. if (this.isCube) {
  54921. if (faceIndex === 5) {
  54922. engine.generateMipMapsForCubemap(this._texture);
  54923. }
  54924. }
  54925. this.unbindFrameBuffer(engine, faceIndex);
  54926. }
  54927. else {
  54928. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54929. }
  54930. };
  54931. /**
  54932. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54933. * This allowed control for front to back rendering or reversly depending of the special needs.
  54934. *
  54935. * @param renderingGroupId The rendering group id corresponding to its index
  54936. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54937. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54938. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54939. */
  54940. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54941. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54942. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54943. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54944. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54945. };
  54946. /**
  54947. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54948. *
  54949. * @param renderingGroupId The rendering group id corresponding to its index
  54950. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54951. */
  54952. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54953. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54954. };
  54955. RenderTargetTexture.prototype.clone = function () {
  54956. var textureSize = this.getSize();
  54957. 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);
  54958. // Base texture
  54959. newTexture.hasAlpha = this.hasAlpha;
  54960. newTexture.level = this.level;
  54961. // RenderTarget Texture
  54962. newTexture.coordinatesMode = this.coordinatesMode;
  54963. if (this.renderList) {
  54964. newTexture.renderList = this.renderList.slice(0);
  54965. }
  54966. return newTexture;
  54967. };
  54968. RenderTargetTexture.prototype.serialize = function () {
  54969. if (!this.name) {
  54970. return null;
  54971. }
  54972. var serializationObject = _super.prototype.serialize.call(this);
  54973. serializationObject.renderTargetSize = this.getRenderSize();
  54974. serializationObject.renderList = [];
  54975. if (this.renderList) {
  54976. for (var index = 0; index < this.renderList.length; index++) {
  54977. serializationObject.renderList.push(this.renderList[index].id);
  54978. }
  54979. }
  54980. return serializationObject;
  54981. };
  54982. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54983. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54984. var objBuffer = this.getInternalTexture();
  54985. var scene = this.getScene();
  54986. if (objBuffer && scene) {
  54987. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54988. }
  54989. };
  54990. RenderTargetTexture.prototype.dispose = function () {
  54991. if (this._postProcessManager) {
  54992. this._postProcessManager.dispose();
  54993. this._postProcessManager = null;
  54994. }
  54995. this.clearPostProcesses(true);
  54996. if (this._resizeObserver) {
  54997. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54998. this._resizeObserver = null;
  54999. }
  55000. this.renderList = null;
  55001. // Remove from custom render targets
  55002. var scene = this.getScene();
  55003. if (!scene) {
  55004. return;
  55005. }
  55006. var index = scene.customRenderTargets.indexOf(this);
  55007. if (index >= 0) {
  55008. scene.customRenderTargets.splice(index, 1);
  55009. }
  55010. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  55011. var camera = _a[_i];
  55012. index = camera.customRenderTargets.indexOf(this);
  55013. if (index >= 0) {
  55014. camera.customRenderTargets.splice(index, 1);
  55015. }
  55016. }
  55017. _super.prototype.dispose.call(this);
  55018. };
  55019. RenderTargetTexture.prototype._rebuild = function () {
  55020. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55021. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55022. }
  55023. if (this._postProcessManager) {
  55024. this._postProcessManager._rebuild();
  55025. }
  55026. };
  55027. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  55028. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  55029. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  55030. return RenderTargetTexture;
  55031. }(BABYLON.Texture));
  55032. BABYLON.RenderTargetTexture = RenderTargetTexture;
  55033. })(BABYLON || (BABYLON = {}));
  55034. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  55035. var BABYLON;
  55036. (function (BABYLON) {
  55037. ;
  55038. var MultiRenderTarget = /** @class */ (function (_super) {
  55039. __extends(MultiRenderTarget, _super);
  55040. function MultiRenderTarget(name, size, count, scene, options) {
  55041. var _this = this;
  55042. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  55043. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  55044. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  55045. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  55046. _this._engine = scene.getEngine();
  55047. if (!_this.isSupported) {
  55048. _this.dispose();
  55049. return;
  55050. }
  55051. var types = [];
  55052. var samplingModes = [];
  55053. for (var i = 0; i < count; i++) {
  55054. if (options && options.types && options.types[i] !== undefined) {
  55055. types.push(options.types[i]);
  55056. }
  55057. else {
  55058. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55059. }
  55060. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  55061. samplingModes.push(options.samplingModes[i]);
  55062. }
  55063. else {
  55064. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55065. }
  55066. }
  55067. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  55068. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  55069. _this._size = size;
  55070. _this._multiRenderTargetOptions = {
  55071. samplingModes: samplingModes,
  55072. generateMipMaps: generateMipMaps,
  55073. generateDepthBuffer: generateDepthBuffer,
  55074. generateStencilBuffer: generateStencilBuffer,
  55075. generateDepthTexture: generateDepthTexture,
  55076. types: types,
  55077. textureCount: count
  55078. };
  55079. _this._createInternalTextures();
  55080. _this._createTextures();
  55081. return _this;
  55082. }
  55083. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  55084. get: function () {
  55085. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  55086. },
  55087. enumerable: true,
  55088. configurable: true
  55089. });
  55090. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  55091. get: function () {
  55092. return this._textures;
  55093. },
  55094. enumerable: true,
  55095. configurable: true
  55096. });
  55097. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  55098. get: function () {
  55099. return this._textures[this._textures.length - 1];
  55100. },
  55101. enumerable: true,
  55102. configurable: true
  55103. });
  55104. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  55105. set: function (wrap) {
  55106. if (this._textures) {
  55107. for (var i = 0; i < this._textures.length; i++) {
  55108. this._textures[i].wrapU = wrap;
  55109. }
  55110. }
  55111. },
  55112. enumerable: true,
  55113. configurable: true
  55114. });
  55115. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  55116. set: function (wrap) {
  55117. if (this._textures) {
  55118. for (var i = 0; i < this._textures.length; i++) {
  55119. this._textures[i].wrapV = wrap;
  55120. }
  55121. }
  55122. },
  55123. enumerable: true,
  55124. configurable: true
  55125. });
  55126. MultiRenderTarget.prototype._rebuild = function () {
  55127. this.releaseInternalTextures();
  55128. this._createInternalTextures();
  55129. for (var i = 0; i < this._internalTextures.length; i++) {
  55130. var texture = this._textures[i];
  55131. texture._texture = this._internalTextures[i];
  55132. }
  55133. // Keeps references to frame buffer and stencil/depth buffer
  55134. this._texture = this._internalTextures[0];
  55135. };
  55136. MultiRenderTarget.prototype._createInternalTextures = function () {
  55137. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  55138. };
  55139. MultiRenderTarget.prototype._createTextures = function () {
  55140. this._textures = [];
  55141. for (var i = 0; i < this._internalTextures.length; i++) {
  55142. var texture = new BABYLON.Texture(null, this.getScene());
  55143. texture._texture = this._internalTextures[i];
  55144. this._textures.push(texture);
  55145. }
  55146. // Keeps references to frame buffer and stencil/depth buffer
  55147. this._texture = this._internalTextures[0];
  55148. };
  55149. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  55150. get: function () {
  55151. return this._samples;
  55152. },
  55153. set: function (value) {
  55154. if (this._samples === value) {
  55155. return;
  55156. }
  55157. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  55158. },
  55159. enumerable: true,
  55160. configurable: true
  55161. });
  55162. MultiRenderTarget.prototype.resize = function (size) {
  55163. this.releaseInternalTextures();
  55164. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  55165. this._createInternalTextures();
  55166. };
  55167. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  55168. var _this = this;
  55169. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  55170. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  55171. });
  55172. };
  55173. MultiRenderTarget.prototype.dispose = function () {
  55174. this.releaseInternalTextures();
  55175. _super.prototype.dispose.call(this);
  55176. };
  55177. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  55178. if (!this._internalTextures) {
  55179. return;
  55180. }
  55181. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  55182. if (this._internalTextures[i] !== undefined) {
  55183. this._internalTextures[i].dispose();
  55184. this._internalTextures.splice(i, 1);
  55185. }
  55186. }
  55187. };
  55188. return MultiRenderTarget;
  55189. }(BABYLON.RenderTargetTexture));
  55190. BABYLON.MultiRenderTarget = MultiRenderTarget;
  55191. })(BABYLON || (BABYLON = {}));
  55192. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  55193. var BABYLON;
  55194. (function (BABYLON) {
  55195. var MirrorTexture = /** @class */ (function (_super) {
  55196. __extends(MirrorTexture, _super);
  55197. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  55198. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55199. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55200. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55201. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  55202. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  55203. _this._transformMatrix = BABYLON.Matrix.Zero();
  55204. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  55205. _this._adaptiveBlurKernel = 0;
  55206. _this._blurKernelX = 0;
  55207. _this._blurKernelY = 0;
  55208. _this._blurRatio = 1.0;
  55209. _this.ignoreCameraViewport = true;
  55210. _this.onBeforeRenderObservable.add(function () {
  55211. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  55212. _this._savedViewMatrix = scene.getViewMatrix();
  55213. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  55214. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  55215. scene.clipPlane = _this.mirrorPlane;
  55216. scene.getEngine().cullBackFaces = false;
  55217. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  55218. });
  55219. _this.onAfterRenderObservable.add(function () {
  55220. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  55221. scene.getEngine().cullBackFaces = true;
  55222. scene._mirroredCameraPosition = null;
  55223. delete scene.clipPlane;
  55224. });
  55225. return _this;
  55226. }
  55227. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  55228. get: function () {
  55229. return this._blurRatio;
  55230. },
  55231. set: function (value) {
  55232. if (this._blurRatio === value) {
  55233. return;
  55234. }
  55235. this._blurRatio = value;
  55236. this._preparePostProcesses();
  55237. },
  55238. enumerable: true,
  55239. configurable: true
  55240. });
  55241. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  55242. set: function (value) {
  55243. this._adaptiveBlurKernel = value;
  55244. this._autoComputeBlurKernel();
  55245. },
  55246. enumerable: true,
  55247. configurable: true
  55248. });
  55249. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  55250. set: function (value) {
  55251. this.blurKernelX = value;
  55252. this.blurKernelY = value;
  55253. },
  55254. enumerable: true,
  55255. configurable: true
  55256. });
  55257. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  55258. get: function () {
  55259. return this._blurKernelX;
  55260. },
  55261. set: function (value) {
  55262. if (this._blurKernelX === value) {
  55263. return;
  55264. }
  55265. this._blurKernelX = value;
  55266. this._preparePostProcesses();
  55267. },
  55268. enumerable: true,
  55269. configurable: true
  55270. });
  55271. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  55272. get: function () {
  55273. return this._blurKernelY;
  55274. },
  55275. set: function (value) {
  55276. if (this._blurKernelY === value) {
  55277. return;
  55278. }
  55279. this._blurKernelY = value;
  55280. this._preparePostProcesses();
  55281. },
  55282. enumerable: true,
  55283. configurable: true
  55284. });
  55285. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  55286. var engine = this.getScene().getEngine();
  55287. var dw = this.getRenderWidth() / engine.getRenderWidth();
  55288. var dh = this.getRenderHeight() / engine.getRenderHeight();
  55289. this.blurKernelX = this._adaptiveBlurKernel * dw;
  55290. this.blurKernelY = this._adaptiveBlurKernel * dh;
  55291. };
  55292. MirrorTexture.prototype._onRatioRescale = function () {
  55293. if (this._sizeRatio) {
  55294. this.resize(this._initialSizeParameter);
  55295. if (!this._adaptiveBlurKernel) {
  55296. this._preparePostProcesses();
  55297. }
  55298. }
  55299. if (this._adaptiveBlurKernel) {
  55300. this._autoComputeBlurKernel();
  55301. }
  55302. };
  55303. MirrorTexture.prototype._preparePostProcesses = function () {
  55304. this.clearPostProcesses(true);
  55305. if (this._blurKernelX && this._blurKernelY) {
  55306. var engine = this.getScene().getEngine();
  55307. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55308. 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);
  55309. this._blurX.autoClear = false;
  55310. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  55311. this._blurX.outputTexture = this._texture;
  55312. }
  55313. else {
  55314. this._blurX.alwaysForcePOT = true;
  55315. }
  55316. 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);
  55317. this._blurY.autoClear = false;
  55318. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  55319. this.addPostProcess(this._blurX);
  55320. this.addPostProcess(this._blurY);
  55321. }
  55322. else {
  55323. if (this._blurY) {
  55324. this.removePostProcess(this._blurY);
  55325. this._blurY.dispose();
  55326. this._blurY = null;
  55327. }
  55328. if (this._blurX) {
  55329. this.removePostProcess(this._blurX);
  55330. this._blurX.dispose();
  55331. this._blurX = null;
  55332. }
  55333. }
  55334. };
  55335. MirrorTexture.prototype.clone = function () {
  55336. var scene = this.getScene();
  55337. if (!scene) {
  55338. return this;
  55339. }
  55340. var textureSize = this.getSize();
  55341. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  55342. // Base texture
  55343. newTexture.hasAlpha = this.hasAlpha;
  55344. newTexture.level = this.level;
  55345. // Mirror Texture
  55346. newTexture.mirrorPlane = this.mirrorPlane.clone();
  55347. if (this.renderList) {
  55348. newTexture.renderList = this.renderList.slice(0);
  55349. }
  55350. return newTexture;
  55351. };
  55352. MirrorTexture.prototype.serialize = function () {
  55353. if (!this.name) {
  55354. return null;
  55355. }
  55356. var serializationObject = _super.prototype.serialize.call(this);
  55357. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  55358. return serializationObject;
  55359. };
  55360. return MirrorTexture;
  55361. }(BABYLON.RenderTargetTexture));
  55362. BABYLON.MirrorTexture = MirrorTexture;
  55363. })(BABYLON || (BABYLON = {}));
  55364. //# sourceMappingURL=babylon.mirrorTexture.js.map
  55365. var BABYLON;
  55366. (function (BABYLON) {
  55367. /**
  55368. * Creates a refraction texture used by refraction channel of the standard material.
  55369. * @param name the texture name
  55370. * @param size size of the underlying texture
  55371. * @param scene root scene
  55372. */
  55373. var RefractionTexture = /** @class */ (function (_super) {
  55374. __extends(RefractionTexture, _super);
  55375. function RefractionTexture(name, size, scene, generateMipMaps) {
  55376. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  55377. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  55378. _this.depth = 2.0;
  55379. _this.onBeforeRenderObservable.add(function () {
  55380. scene.clipPlane = _this.refractionPlane;
  55381. });
  55382. _this.onAfterRenderObservable.add(function () {
  55383. delete scene.clipPlane;
  55384. });
  55385. return _this;
  55386. }
  55387. RefractionTexture.prototype.clone = function () {
  55388. var scene = this.getScene();
  55389. if (!scene) {
  55390. return this;
  55391. }
  55392. var textureSize = this.getSize();
  55393. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  55394. // Base texture
  55395. newTexture.hasAlpha = this.hasAlpha;
  55396. newTexture.level = this.level;
  55397. // Refraction Texture
  55398. newTexture.refractionPlane = this.refractionPlane.clone();
  55399. if (this.renderList) {
  55400. newTexture.renderList = this.renderList.slice(0);
  55401. }
  55402. newTexture.depth = this.depth;
  55403. return newTexture;
  55404. };
  55405. RefractionTexture.prototype.serialize = function () {
  55406. if (!this.name) {
  55407. return null;
  55408. }
  55409. var serializationObject = _super.prototype.serialize.call(this);
  55410. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  55411. serializationObject.depth = this.depth;
  55412. return serializationObject;
  55413. };
  55414. return RefractionTexture;
  55415. }(BABYLON.RenderTargetTexture));
  55416. BABYLON.RefractionTexture = RefractionTexture;
  55417. })(BABYLON || (BABYLON = {}));
  55418. //# sourceMappingURL=babylon.refractionTexture.js.map
  55419. var BABYLON;
  55420. (function (BABYLON) {
  55421. var DynamicTexture = /** @class */ (function (_super) {
  55422. __extends(DynamicTexture, _super);
  55423. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  55424. if (scene === void 0) { scene = null; }
  55425. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55426. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55427. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  55428. _this.name = name;
  55429. _this._engine = _this.getScene().getEngine();
  55430. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55431. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55432. _this._generateMipMaps = generateMipMaps;
  55433. if (options.getContext) {
  55434. _this._canvas = options;
  55435. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55436. }
  55437. else {
  55438. _this._canvas = document.createElement("canvas");
  55439. if (options.width) {
  55440. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55441. }
  55442. else {
  55443. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  55444. }
  55445. }
  55446. var textureSize = _this.getSize();
  55447. _this._canvas.width = textureSize.width;
  55448. _this._canvas.height = textureSize.height;
  55449. _this._context = _this._canvas.getContext("2d");
  55450. return _this;
  55451. }
  55452. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  55453. get: function () {
  55454. return true;
  55455. },
  55456. enumerable: true,
  55457. configurable: true
  55458. });
  55459. DynamicTexture.prototype._recreate = function (textureSize) {
  55460. this._canvas.width = textureSize.width;
  55461. this._canvas.height = textureSize.height;
  55462. this.releaseInternalTexture();
  55463. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  55464. };
  55465. DynamicTexture.prototype.scale = function (ratio) {
  55466. var textureSize = this.getSize();
  55467. textureSize.width *= ratio;
  55468. textureSize.height *= ratio;
  55469. this._recreate(textureSize);
  55470. };
  55471. DynamicTexture.prototype.scaleTo = function (width, height) {
  55472. var textureSize = this.getSize();
  55473. textureSize.width = width;
  55474. textureSize.height = height;
  55475. this._recreate(textureSize);
  55476. };
  55477. DynamicTexture.prototype.getContext = function () {
  55478. return this._context;
  55479. };
  55480. DynamicTexture.prototype.clear = function () {
  55481. var size = this.getSize();
  55482. this._context.fillRect(0, 0, size.width, size.height);
  55483. };
  55484. DynamicTexture.prototype.update = function (invertY) {
  55485. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  55486. };
  55487. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  55488. if (update === void 0) { update = true; }
  55489. var size = this.getSize();
  55490. if (clearColor) {
  55491. this._context.fillStyle = clearColor;
  55492. this._context.fillRect(0, 0, size.width, size.height);
  55493. }
  55494. this._context.font = font;
  55495. if (x === null || x === undefined) {
  55496. var textSize = this._context.measureText(text);
  55497. x = (size.width - textSize.width) / 2;
  55498. }
  55499. if (y === null || y === undefined) {
  55500. var fontSize = parseInt((font.replace(/\D/g, '')));
  55501. ;
  55502. y = (size.height / 2) + (fontSize / 3.65);
  55503. }
  55504. this._context.fillStyle = color;
  55505. this._context.fillText(text, x, y);
  55506. if (update) {
  55507. this.update(invertY);
  55508. }
  55509. };
  55510. DynamicTexture.prototype.clone = function () {
  55511. var scene = this.getScene();
  55512. if (!scene) {
  55513. return this;
  55514. }
  55515. var textureSize = this.getSize();
  55516. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  55517. // Base texture
  55518. newTexture.hasAlpha = this.hasAlpha;
  55519. newTexture.level = this.level;
  55520. // Dynamic Texture
  55521. newTexture.wrapU = this.wrapU;
  55522. newTexture.wrapV = this.wrapV;
  55523. return newTexture;
  55524. };
  55525. DynamicTexture.prototype._rebuild = function () {
  55526. this.update();
  55527. };
  55528. return DynamicTexture;
  55529. }(BABYLON.Texture));
  55530. BABYLON.DynamicTexture = DynamicTexture;
  55531. })(BABYLON || (BABYLON = {}));
  55532. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55533. var BABYLON;
  55534. (function (BABYLON) {
  55535. var VideoTexture = /** @class */ (function (_super) {
  55536. __extends(VideoTexture, _super);
  55537. /**
  55538. * Creates a video texture.
  55539. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55540. * @param {string | null} name optional name, will detect from video source, if not defined
  55541. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55542. * @param {BABYLON.Scene} scene is obviously the current scene.
  55543. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55544. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55545. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55546. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55547. */
  55548. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55549. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55550. if (invertY === void 0) { invertY = false; }
  55551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55552. if (settings === void 0) { settings = {
  55553. autoPlay: true,
  55554. loop: true,
  55555. autoUpdateTexture: true,
  55556. }; }
  55557. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55558. _this._createInternalTexture = function () {
  55559. if (_this._texture != null) {
  55560. return;
  55561. }
  55562. if (!_this._engine.needPOTTextures ||
  55563. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55564. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55565. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55566. }
  55567. else {
  55568. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55569. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55570. _this._generateMipMaps = false;
  55571. }
  55572. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55573. _this._texture.isReady = true;
  55574. _this._updateInternalTexture();
  55575. };
  55576. _this.reset = function () {
  55577. if (_this._texture == null) {
  55578. return;
  55579. }
  55580. _this._texture.dispose();
  55581. _this._texture = null;
  55582. };
  55583. _this._updateInternalTexture = function (e) {
  55584. if (_this._texture == null || !_this._texture.isReady) {
  55585. return;
  55586. }
  55587. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55588. return;
  55589. }
  55590. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55591. };
  55592. _this._engine = _this.getScene().getEngine();
  55593. _this._generateMipMaps = generateMipMaps;
  55594. _this._samplingMode = samplingMode;
  55595. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55596. _this.name = name || _this._getName(src);
  55597. _this.video = _this._getVideo(src);
  55598. if (settings.autoPlay !== undefined) {
  55599. _this.video.autoplay = settings.autoPlay;
  55600. }
  55601. if (settings.loop !== undefined) {
  55602. _this.video.loop = settings.loop;
  55603. }
  55604. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55605. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55606. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55607. _this.video.addEventListener("emptied", _this.reset);
  55608. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55609. _this._createInternalTexture();
  55610. }
  55611. return _this;
  55612. }
  55613. VideoTexture.prototype._getName = function (src) {
  55614. if (src instanceof HTMLVideoElement) {
  55615. return src.currentSrc;
  55616. }
  55617. if (typeof src === "object") {
  55618. return src.toString();
  55619. }
  55620. return src;
  55621. };
  55622. ;
  55623. VideoTexture.prototype._getVideo = function (src) {
  55624. if (src instanceof HTMLVideoElement) {
  55625. return src;
  55626. }
  55627. var video = document.createElement("video");
  55628. if (typeof src === "string") {
  55629. video.src = src;
  55630. }
  55631. else {
  55632. src.forEach(function (url) {
  55633. var source = document.createElement("source");
  55634. source.src = url;
  55635. video.appendChild(source);
  55636. });
  55637. }
  55638. return video;
  55639. };
  55640. ;
  55641. /**
  55642. * Internal method to initiate `update`.
  55643. */
  55644. VideoTexture.prototype._rebuild = function () {
  55645. this.update();
  55646. };
  55647. /**
  55648. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55649. */
  55650. VideoTexture.prototype.update = function () {
  55651. if (!this.autoUpdateTexture) {
  55652. // Expecting user to call `updateTexture` manually
  55653. return;
  55654. }
  55655. this.updateTexture(true);
  55656. };
  55657. /**
  55658. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55659. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55660. */
  55661. VideoTexture.prototype.updateTexture = function (isVisible) {
  55662. if (!isVisible) {
  55663. return;
  55664. }
  55665. if (this.video.paused) {
  55666. return;
  55667. }
  55668. this._updateInternalTexture();
  55669. };
  55670. /**
  55671. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55672. * @param url New url.
  55673. */
  55674. VideoTexture.prototype.updateURL = function (url) {
  55675. this.video.src = url;
  55676. };
  55677. VideoTexture.prototype.dispose = function () {
  55678. _super.prototype.dispose.call(this);
  55679. this.video.removeEventListener("canplay", this._createInternalTexture);
  55680. this.video.removeEventListener("paused", this._updateInternalTexture);
  55681. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55682. this.video.removeEventListener("emptied", this.reset);
  55683. };
  55684. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55685. var video = document.createElement("video");
  55686. var constraintsDeviceId;
  55687. if (constraints && constraints.deviceId) {
  55688. constraintsDeviceId = {
  55689. exact: constraints.deviceId,
  55690. };
  55691. }
  55692. navigator.getUserMedia =
  55693. navigator.getUserMedia ||
  55694. navigator.webkitGetUserMedia ||
  55695. navigator.mozGetUserMedia ||
  55696. navigator.msGetUserMedia;
  55697. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55698. if (navigator.getUserMedia) {
  55699. navigator.getUserMedia({
  55700. video: {
  55701. deviceId: constraintsDeviceId,
  55702. width: {
  55703. min: (constraints && constraints.minWidth) || 256,
  55704. max: (constraints && constraints.maxWidth) || 640,
  55705. },
  55706. height: {
  55707. min: (constraints && constraints.minHeight) || 256,
  55708. max: (constraints && constraints.maxHeight) || 480,
  55709. },
  55710. },
  55711. }, function (stream) {
  55712. if (video.mozSrcObject !== undefined) {
  55713. // hack for Firefox < 19
  55714. video.mozSrcObject = stream;
  55715. }
  55716. else {
  55717. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55718. }
  55719. video.play();
  55720. if (onReady) {
  55721. onReady(new VideoTexture("video", video, scene, true, true));
  55722. }
  55723. }, function (e) {
  55724. BABYLON.Tools.Error(e.name);
  55725. });
  55726. }
  55727. };
  55728. return VideoTexture;
  55729. }(BABYLON.Texture));
  55730. BABYLON.VideoTexture = VideoTexture;
  55731. })(BABYLON || (BABYLON = {}));
  55732. //# sourceMappingURL=babylon.videoTexture.js.map
  55733. var BABYLON;
  55734. (function (BABYLON) {
  55735. var RawTexture = /** @class */ (function (_super) {
  55736. __extends(RawTexture, _super);
  55737. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55738. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55739. if (invertY === void 0) { invertY = false; }
  55740. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55741. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55742. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55743. _this.format = format;
  55744. _this._engine = scene.getEngine();
  55745. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55746. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55747. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55748. return _this;
  55749. }
  55750. RawTexture.prototype.update = function (data) {
  55751. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55752. };
  55753. // Statics
  55754. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55755. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55756. if (invertY === void 0) { invertY = false; }
  55757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55758. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55759. };
  55760. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55761. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55762. if (invertY === void 0) { invertY = false; }
  55763. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55764. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55765. };
  55766. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55767. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55768. if (invertY === void 0) { invertY = false; }
  55769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55770. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55771. };
  55772. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55773. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55774. if (invertY === void 0) { invertY = false; }
  55775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55776. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55777. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55778. };
  55779. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55780. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55781. if (invertY === void 0) { invertY = false; }
  55782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55783. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55784. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55785. };
  55786. return RawTexture;
  55787. }(BABYLON.Texture));
  55788. BABYLON.RawTexture = RawTexture;
  55789. })(BABYLON || (BABYLON = {}));
  55790. //# sourceMappingURL=babylon.rawTexture.js.map
  55791. var BABYLON;
  55792. (function (BABYLON) {
  55793. var PostProcess = /** @class */ (function () {
  55794. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55796. if (defines === void 0) { defines = null; }
  55797. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55798. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55799. if (blockCompilation === void 0) { blockCompilation = false; }
  55800. this.name = name;
  55801. this.width = -1;
  55802. this.height = -1;
  55803. this.autoClear = true;
  55804. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55805. this.animations = new Array();
  55806. /*
  55807. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55808. Can only be used on a single postprocess or on the last one of a chain.
  55809. */
  55810. this.enablePixelPerfectMode = false;
  55811. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55812. this.alwaysForcePOT = false;
  55813. this.samples = 1;
  55814. this.adaptScaleToCurrentViewport = false;
  55815. this._reusable = false;
  55816. this._textures = new BABYLON.SmartArray(2);
  55817. this._currentRenderTextureInd = 0;
  55818. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55819. this._texelSize = BABYLON.Vector2.Zero();
  55820. // Events
  55821. /**
  55822. * An event triggered when the postprocess is activated.
  55823. * @type {BABYLON.Observable}
  55824. */
  55825. this.onActivateObservable = new BABYLON.Observable();
  55826. /**
  55827. * An event triggered when the postprocess changes its size.
  55828. * @type {BABYLON.Observable}
  55829. */
  55830. this.onSizeChangedObservable = new BABYLON.Observable();
  55831. /**
  55832. * An event triggered when the postprocess applies its effect.
  55833. * @type {BABYLON.Observable}
  55834. */
  55835. this.onApplyObservable = new BABYLON.Observable();
  55836. /**
  55837. * An event triggered before rendering the postprocess
  55838. * @type {BABYLON.Observable}
  55839. */
  55840. this.onBeforeRenderObservable = new BABYLON.Observable();
  55841. /**
  55842. * An event triggered after rendering the postprocess
  55843. * @type {BABYLON.Observable}
  55844. */
  55845. this.onAfterRenderObservable = new BABYLON.Observable();
  55846. if (camera != null) {
  55847. this._camera = camera;
  55848. this._scene = camera.getScene();
  55849. camera.attachPostProcess(this);
  55850. this._engine = this._scene.getEngine();
  55851. this._scene.postProcesses.push(this);
  55852. }
  55853. else if (engine) {
  55854. this._engine = engine;
  55855. this._engine.postProcesses.push(this);
  55856. }
  55857. this._options = options;
  55858. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55859. this._reusable = reusable || false;
  55860. this._textureType = textureType;
  55861. this._samplers = samplers || [];
  55862. this._samplers.push("textureSampler");
  55863. this._fragmentUrl = fragmentUrl;
  55864. this._vertexUrl = vertexUrl;
  55865. this._parameters = parameters || [];
  55866. this._parameters.push("scale");
  55867. this._indexParameters = indexParameters;
  55868. if (!blockCompilation) {
  55869. this.updateEffect(defines);
  55870. }
  55871. }
  55872. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55873. set: function (callback) {
  55874. if (this._onActivateObserver) {
  55875. this.onActivateObservable.remove(this._onActivateObserver);
  55876. }
  55877. if (callback) {
  55878. this._onActivateObserver = this.onActivateObservable.add(callback);
  55879. }
  55880. },
  55881. enumerable: true,
  55882. configurable: true
  55883. });
  55884. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55885. set: function (callback) {
  55886. if (this._onSizeChangedObserver) {
  55887. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55888. }
  55889. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55890. },
  55891. enumerable: true,
  55892. configurable: true
  55893. });
  55894. Object.defineProperty(PostProcess.prototype, "onApply", {
  55895. set: function (callback) {
  55896. if (this._onApplyObserver) {
  55897. this.onApplyObservable.remove(this._onApplyObserver);
  55898. }
  55899. this._onApplyObserver = this.onApplyObservable.add(callback);
  55900. },
  55901. enumerable: true,
  55902. configurable: true
  55903. });
  55904. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55905. set: function (callback) {
  55906. if (this._onBeforeRenderObserver) {
  55907. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55908. }
  55909. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55910. },
  55911. enumerable: true,
  55912. configurable: true
  55913. });
  55914. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55915. set: function (callback) {
  55916. if (this._onAfterRenderObserver) {
  55917. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55918. }
  55919. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55920. },
  55921. enumerable: true,
  55922. configurable: true
  55923. });
  55924. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55925. get: function () {
  55926. return this._textures.data[this._currentRenderTextureInd];
  55927. },
  55928. set: function (value) {
  55929. this._forcedOutputTexture = value;
  55930. },
  55931. enumerable: true,
  55932. configurable: true
  55933. });
  55934. PostProcess.prototype.getCamera = function () {
  55935. return this._camera;
  55936. };
  55937. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55938. get: function () {
  55939. if (this._shareOutputWithPostProcess) {
  55940. return this._shareOutputWithPostProcess.texelSize;
  55941. }
  55942. if (this._forcedOutputTexture) {
  55943. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55944. }
  55945. return this._texelSize;
  55946. },
  55947. enumerable: true,
  55948. configurable: true
  55949. });
  55950. PostProcess.prototype.getEngine = function () {
  55951. return this._engine;
  55952. };
  55953. PostProcess.prototype.getEffect = function () {
  55954. return this._effect;
  55955. };
  55956. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55957. this._disposeTextures();
  55958. this._shareOutputWithPostProcess = postProcess;
  55959. return this;
  55960. };
  55961. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55962. if (defines === void 0) { defines = null; }
  55963. if (uniforms === void 0) { uniforms = null; }
  55964. if (samplers === void 0) { samplers = null; }
  55965. 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);
  55966. };
  55967. PostProcess.prototype.isReusable = function () {
  55968. return this._reusable;
  55969. };
  55970. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55971. PostProcess.prototype.markTextureDirty = function () {
  55972. this.width = -1;
  55973. };
  55974. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55975. var _this = this;
  55976. if (sourceTexture === void 0) { sourceTexture = null; }
  55977. camera = camera || this._camera;
  55978. var scene = camera.getScene();
  55979. var engine = scene.getEngine();
  55980. var maxSize = engine.getCaps().maxTextureSize;
  55981. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55982. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55983. var desiredWidth = (this._options.width || requiredWidth);
  55984. var desiredHeight = this._options.height || requiredHeight;
  55985. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55986. if (this.adaptScaleToCurrentViewport) {
  55987. var currentViewport = engine.currentViewport;
  55988. if (currentViewport) {
  55989. desiredWidth *= currentViewport.width;
  55990. desiredHeight *= currentViewport.height;
  55991. }
  55992. }
  55993. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55994. if (!this._options.width) {
  55995. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55996. }
  55997. if (!this._options.height) {
  55998. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55999. }
  56000. }
  56001. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  56002. if (this._textures.length > 0) {
  56003. for (var i = 0; i < this._textures.length; i++) {
  56004. this._engine._releaseTexture(this._textures.data[i]);
  56005. }
  56006. this._textures.reset();
  56007. }
  56008. this.width = desiredWidth;
  56009. this.height = desiredHeight;
  56010. var textureSize = { width: this.width, height: this.height };
  56011. var textureOptions = {
  56012. generateMipMaps: false,
  56013. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  56014. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  56015. samplingMode: this.renderTargetSamplingMode,
  56016. type: this._textureType
  56017. };
  56018. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56019. if (this._reusable) {
  56020. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56021. }
  56022. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  56023. this.onSizeChangedObservable.notifyObservers(this);
  56024. }
  56025. this._textures.forEach(function (texture) {
  56026. if (texture.samples !== _this.samples) {
  56027. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  56028. }
  56029. });
  56030. }
  56031. var target;
  56032. if (this._shareOutputWithPostProcess) {
  56033. target = this._shareOutputWithPostProcess.outputTexture;
  56034. }
  56035. else if (this._forcedOutputTexture) {
  56036. target = this._forcedOutputTexture;
  56037. this.width = this._forcedOutputTexture.width;
  56038. this.height = this._forcedOutputTexture.height;
  56039. }
  56040. else {
  56041. target = this.outputTexture;
  56042. }
  56043. if (this.enablePixelPerfectMode) {
  56044. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  56045. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  56046. }
  56047. else {
  56048. this._scaleRatio.copyFromFloats(1, 1);
  56049. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  56050. }
  56051. this.onActivateObservable.notifyObservers(camera);
  56052. // Clear
  56053. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  56054. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  56055. }
  56056. if (this._reusable) {
  56057. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  56058. }
  56059. };
  56060. Object.defineProperty(PostProcess.prototype, "isSupported", {
  56061. get: function () {
  56062. return this._effect.isSupported;
  56063. },
  56064. enumerable: true,
  56065. configurable: true
  56066. });
  56067. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  56068. get: function () {
  56069. if (this._shareOutputWithPostProcess) {
  56070. return this._shareOutputWithPostProcess.aspectRatio;
  56071. }
  56072. if (this._forcedOutputTexture) {
  56073. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  56074. }
  56075. return this.width / this.height;
  56076. },
  56077. enumerable: true,
  56078. configurable: true
  56079. });
  56080. /**
  56081. * Get a value indicating if the post-process is ready to be used
  56082. * @returns true if the post-process is ready (shader is compiled)
  56083. */
  56084. PostProcess.prototype.isReady = function () {
  56085. return this._effect && this._effect.isReady();
  56086. };
  56087. PostProcess.prototype.apply = function () {
  56088. // Check
  56089. if (!this._effect || !this._effect.isReady())
  56090. return null;
  56091. // States
  56092. this._engine.enableEffect(this._effect);
  56093. this._engine.setState(false);
  56094. this._engine.setDepthBuffer(false);
  56095. this._engine.setDepthWrite(false);
  56096. // Alpha
  56097. this._engine.setAlphaMode(this.alphaMode);
  56098. if (this.alphaConstants) {
  56099. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  56100. }
  56101. // Texture
  56102. var source;
  56103. if (this._shareOutputWithPostProcess) {
  56104. source = this._shareOutputWithPostProcess.outputTexture;
  56105. }
  56106. else if (this._forcedOutputTexture) {
  56107. source = this._forcedOutputTexture;
  56108. }
  56109. else {
  56110. source = this.outputTexture;
  56111. }
  56112. this._effect._bindTexture("textureSampler", source);
  56113. // Parameters
  56114. this._effect.setVector2("scale", this._scaleRatio);
  56115. this.onApplyObservable.notifyObservers(this._effect);
  56116. return this._effect;
  56117. };
  56118. PostProcess.prototype._disposeTextures = function () {
  56119. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  56120. return;
  56121. }
  56122. if (this._textures.length > 0) {
  56123. for (var i = 0; i < this._textures.length; i++) {
  56124. this._engine._releaseTexture(this._textures.data[i]);
  56125. }
  56126. }
  56127. this._textures.dispose();
  56128. };
  56129. PostProcess.prototype.dispose = function (camera) {
  56130. camera = camera || this._camera;
  56131. this._disposeTextures();
  56132. if (this._scene) {
  56133. var index_1 = this._scene.postProcesses.indexOf(this);
  56134. if (index_1 !== -1) {
  56135. this._scene.postProcesses.splice(index_1, 1);
  56136. }
  56137. }
  56138. else {
  56139. var index_2 = this._engine.postProcesses.indexOf(this);
  56140. if (index_2 !== -1) {
  56141. this._engine.postProcesses.splice(index_2, 1);
  56142. }
  56143. }
  56144. if (!camera) {
  56145. return;
  56146. }
  56147. camera.detachPostProcess(this);
  56148. var index = camera._postProcesses.indexOf(this);
  56149. if (index === 0 && camera._postProcesses.length > 0) {
  56150. this._camera._postProcesses[0].markTextureDirty();
  56151. }
  56152. this.onActivateObservable.clear();
  56153. this.onAfterRenderObservable.clear();
  56154. this.onApplyObservable.clear();
  56155. this.onBeforeRenderObservable.clear();
  56156. this.onSizeChangedObservable.clear();
  56157. };
  56158. return PostProcess;
  56159. }());
  56160. BABYLON.PostProcess = PostProcess;
  56161. })(BABYLON || (BABYLON = {}));
  56162. //# sourceMappingURL=babylon.postProcess.js.map
  56163. var BABYLON;
  56164. (function (BABYLON) {
  56165. var PassPostProcess = /** @class */ (function (_super) {
  56166. __extends(PassPostProcess, _super);
  56167. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56168. if (camera === void 0) { camera = null; }
  56169. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56170. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  56171. }
  56172. return PassPostProcess;
  56173. }(BABYLON.PostProcess));
  56174. BABYLON.PassPostProcess = PassPostProcess;
  56175. })(BABYLON || (BABYLON = {}));
  56176. //# sourceMappingURL=babylon.passPostProcess.js.map
  56177. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56178. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56179. s = arguments[i];
  56180. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56181. t[p] = s[p];
  56182. }
  56183. return t;
  56184. };
  56185. var BABYLON;
  56186. (function (BABYLON) {
  56187. /**
  56188. * Default implementation of @see IShadowGenerator.
  56189. * This is the main object responsible of generating shadows in the framework.
  56190. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  56191. */
  56192. var ShadowGenerator = /** @class */ (function () {
  56193. /**
  56194. * Creates a ShadowGenerator object.
  56195. * A ShadowGenerator is the required tool to use the shadows.
  56196. * Each light casting shadows needs to use its own ShadowGenerator.
  56197. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  56198. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  56199. * @param light The light object generating the shadows.
  56200. * @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.
  56201. */
  56202. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  56203. this._bias = 0.00005;
  56204. this._blurBoxOffset = 1;
  56205. this._blurScale = 2;
  56206. this._blurKernel = 1;
  56207. this._useKernelBlur = false;
  56208. this._filter = ShadowGenerator.FILTER_NONE;
  56209. this._darkness = 0;
  56210. this._transparencyShadow = false;
  56211. /**
  56212. * Controls the extent to which the shadows fade out at the edge of the frustum
  56213. * Used only by directionals and spots
  56214. */
  56215. this.frustumEdgeFalloff = 0;
  56216. /**
  56217. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  56218. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  56219. * It might on the other hand introduce peter panning.
  56220. */
  56221. this.forceBackFacesOnly = false;
  56222. this._lightDirection = BABYLON.Vector3.Zero();
  56223. this._viewMatrix = BABYLON.Matrix.Zero();
  56224. this._projectionMatrix = BABYLON.Matrix.Zero();
  56225. this._transformMatrix = BABYLON.Matrix.Zero();
  56226. this._currentFaceIndex = 0;
  56227. this._currentFaceIndexCache = 0;
  56228. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  56229. this._mapSize = mapSize;
  56230. this._light = light;
  56231. this._scene = light.getScene();
  56232. light._shadowGenerator = this;
  56233. // Texture type fallback from float to int if not supported.
  56234. var caps = this._scene.getEngine().getCaps();
  56235. if (!useFullFloatFirst) {
  56236. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56237. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56238. }
  56239. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56240. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56241. }
  56242. else {
  56243. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56244. }
  56245. }
  56246. else {
  56247. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56248. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56249. }
  56250. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56251. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56252. }
  56253. else {
  56254. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56255. }
  56256. }
  56257. this._initializeGenerator();
  56258. }
  56259. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  56260. /**
  56261. * Shadow generator mode None: no filtering applied.
  56262. */
  56263. get: function () {
  56264. return ShadowGenerator._FILTER_NONE;
  56265. },
  56266. enumerable: true,
  56267. configurable: true
  56268. });
  56269. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  56270. /**
  56271. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  56272. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  56273. */
  56274. get: function () {
  56275. return ShadowGenerator._FILTER_POISSONSAMPLING;
  56276. },
  56277. enumerable: true,
  56278. configurable: true
  56279. });
  56280. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  56281. /**
  56282. * Shadow generator mode ESM: Exponential Shadow Mapping.
  56283. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56284. */
  56285. get: function () {
  56286. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  56287. },
  56288. enumerable: true,
  56289. configurable: true
  56290. });
  56291. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  56292. /**
  56293. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  56294. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56295. */
  56296. get: function () {
  56297. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  56298. },
  56299. enumerable: true,
  56300. configurable: true
  56301. });
  56302. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  56303. /**
  56304. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  56305. * edge artifacts on steep falloff.
  56306. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56307. */
  56308. get: function () {
  56309. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56310. },
  56311. enumerable: true,
  56312. configurable: true
  56313. });
  56314. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  56315. /**
  56316. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  56317. * edge artifacts on steep falloff.
  56318. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56319. */
  56320. get: function () {
  56321. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56322. },
  56323. enumerable: true,
  56324. configurable: true
  56325. });
  56326. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  56327. /**
  56328. * Gets the bias: offset applied on the depth preventing acnea.
  56329. */
  56330. get: function () {
  56331. return this._bias;
  56332. },
  56333. /**
  56334. * Sets the bias: offset applied on the depth preventing acnea.
  56335. */
  56336. set: function (bias) {
  56337. this._bias = bias;
  56338. },
  56339. enumerable: true,
  56340. configurable: true
  56341. });
  56342. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  56343. /**
  56344. * Gets the blur box offset: offset applied during the blur pass.
  56345. * Only usefull if useKernelBlur = false
  56346. */
  56347. get: function () {
  56348. return this._blurBoxOffset;
  56349. },
  56350. /**
  56351. * Sets the blur box offset: offset applied during the blur pass.
  56352. * Only usefull if useKernelBlur = false
  56353. */
  56354. set: function (value) {
  56355. if (this._blurBoxOffset === value) {
  56356. return;
  56357. }
  56358. this._blurBoxOffset = value;
  56359. this._disposeBlurPostProcesses();
  56360. },
  56361. enumerable: true,
  56362. configurable: true
  56363. });
  56364. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  56365. /**
  56366. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  56367. * 2 means half of the size.
  56368. */
  56369. get: function () {
  56370. return this._blurScale;
  56371. },
  56372. /**
  56373. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  56374. * 2 means half of the size.
  56375. */
  56376. set: function (value) {
  56377. if (this._blurScale === value) {
  56378. return;
  56379. }
  56380. this._blurScale = value;
  56381. this._disposeBlurPostProcesses();
  56382. },
  56383. enumerable: true,
  56384. configurable: true
  56385. });
  56386. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  56387. /**
  56388. * Gets the blur kernel: kernel size of the blur pass.
  56389. * Only usefull if useKernelBlur = true
  56390. */
  56391. get: function () {
  56392. return this._blurKernel;
  56393. },
  56394. /**
  56395. * Sets the blur kernel: kernel size of the blur pass.
  56396. * Only usefull if useKernelBlur = true
  56397. */
  56398. set: function (value) {
  56399. if (this._blurKernel === value) {
  56400. return;
  56401. }
  56402. this._blurKernel = value;
  56403. this._disposeBlurPostProcesses();
  56404. },
  56405. enumerable: true,
  56406. configurable: true
  56407. });
  56408. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  56409. /**
  56410. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  56411. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56412. */
  56413. get: function () {
  56414. return this._useKernelBlur;
  56415. },
  56416. /**
  56417. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  56418. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56419. */
  56420. set: function (value) {
  56421. if (this._useKernelBlur === value) {
  56422. return;
  56423. }
  56424. this._useKernelBlur = value;
  56425. this._disposeBlurPostProcesses();
  56426. },
  56427. enumerable: true,
  56428. configurable: true
  56429. });
  56430. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  56431. /**
  56432. * Gets the depth scale used in ESM mode.
  56433. */
  56434. get: function () {
  56435. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  56436. },
  56437. /**
  56438. * Sets the depth scale used in ESM mode.
  56439. * This can override the scale stored on the light.
  56440. */
  56441. set: function (value) {
  56442. this._depthScale = value;
  56443. },
  56444. enumerable: true,
  56445. configurable: true
  56446. });
  56447. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  56448. /**
  56449. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  56450. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56451. */
  56452. get: function () {
  56453. return this._filter;
  56454. },
  56455. /**
  56456. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  56457. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56458. */
  56459. set: function (value) {
  56460. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  56461. if (this._light.needCube()) {
  56462. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56463. this.useExponentialShadowMap = true;
  56464. return;
  56465. }
  56466. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56467. this.useCloseExponentialShadowMap = true;
  56468. return;
  56469. }
  56470. }
  56471. if (this._filter === value) {
  56472. return;
  56473. }
  56474. this._filter = value;
  56475. this._disposeBlurPostProcesses();
  56476. this._applyFilterValues();
  56477. this._light._markMeshesAsLightDirty();
  56478. },
  56479. enumerable: true,
  56480. configurable: true
  56481. });
  56482. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  56483. /**
  56484. * Gets if the current filter is set to Poisson Sampling aka PCF.
  56485. */
  56486. get: function () {
  56487. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  56488. },
  56489. /**
  56490. * Sets the current filter to Poisson Sampling aka PCF.
  56491. */
  56492. set: function (value) {
  56493. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  56494. return;
  56495. }
  56496. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  56497. },
  56498. enumerable: true,
  56499. configurable: true
  56500. });
  56501. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  56502. /**
  56503. * Gets if the current filter is set to VSM.
  56504. * DEPRECATED. Should use useExponentialShadowMap instead.
  56505. */
  56506. get: function () {
  56507. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56508. return this.useExponentialShadowMap;
  56509. },
  56510. /**
  56511. * Sets the current filter is to VSM.
  56512. * DEPRECATED. Should use useExponentialShadowMap instead.
  56513. */
  56514. set: function (value) {
  56515. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56516. this.useExponentialShadowMap = value;
  56517. },
  56518. enumerable: true,
  56519. configurable: true
  56520. });
  56521. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  56522. /**
  56523. * Gets if the current filter is set to blurred VSM.
  56524. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56525. */
  56526. get: function () {
  56527. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56528. return this.useBlurExponentialShadowMap;
  56529. },
  56530. /**
  56531. * Sets the current filter is to blurred VSM.
  56532. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56533. */
  56534. set: function (value) {
  56535. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56536. this.useBlurExponentialShadowMap = value;
  56537. },
  56538. enumerable: true,
  56539. configurable: true
  56540. });
  56541. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  56542. /**
  56543. * Gets if the current filter is set to ESM.
  56544. */
  56545. get: function () {
  56546. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  56547. },
  56548. /**
  56549. * Sets the current filter is to ESM.
  56550. */
  56551. set: function (value) {
  56552. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  56553. return;
  56554. }
  56555. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56556. },
  56557. enumerable: true,
  56558. configurable: true
  56559. });
  56560. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  56561. /**
  56562. * Gets if the current filter is set to filtered ESM.
  56563. */
  56564. get: function () {
  56565. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  56566. },
  56567. /**
  56568. * Gets if the current filter is set to filtered ESM.
  56569. */
  56570. set: function (value) {
  56571. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56572. return;
  56573. }
  56574. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56575. },
  56576. enumerable: true,
  56577. configurable: true
  56578. });
  56579. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  56580. /**
  56581. * Gets if the current filter is set to "close ESM" (using the inverse of the
  56582. * exponential to prevent steep falloff artifacts).
  56583. */
  56584. get: function () {
  56585. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56586. },
  56587. /**
  56588. * Sets the current filter to "close ESM" (using the inverse of the
  56589. * exponential to prevent steep falloff artifacts).
  56590. */
  56591. set: function (value) {
  56592. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  56593. return;
  56594. }
  56595. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56596. },
  56597. enumerable: true,
  56598. configurable: true
  56599. });
  56600. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  56601. /**
  56602. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  56603. * exponential to prevent steep falloff artifacts).
  56604. */
  56605. get: function () {
  56606. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56607. },
  56608. /**
  56609. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  56610. * exponential to prevent steep falloff artifacts).
  56611. */
  56612. set: function (value) {
  56613. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56614. return;
  56615. }
  56616. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56617. },
  56618. enumerable: true,
  56619. configurable: true
  56620. });
  56621. /**
  56622. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  56623. * 0 means strongest and 1 would means no shadow.
  56624. * @returns the darkness.
  56625. */
  56626. ShadowGenerator.prototype.getDarkness = function () {
  56627. return this._darkness;
  56628. };
  56629. /**
  56630. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  56631. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  56632. * @returns the shadow generator allowing fluent coding.
  56633. */
  56634. ShadowGenerator.prototype.setDarkness = function (darkness) {
  56635. if (darkness >= 1.0)
  56636. this._darkness = 1.0;
  56637. else if (darkness <= 0.0)
  56638. this._darkness = 0.0;
  56639. else
  56640. this._darkness = darkness;
  56641. return this;
  56642. };
  56643. /**
  56644. * Sets the ability to have transparent shadow (boolean).
  56645. * @param transparent True if transparent else False
  56646. * @returns the shadow generator allowing fluent coding
  56647. */
  56648. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  56649. this._transparencyShadow = transparent;
  56650. return this;
  56651. };
  56652. /**
  56653. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  56654. * @returns The render target texture if present otherwise, null
  56655. */
  56656. ShadowGenerator.prototype.getShadowMap = function () {
  56657. return this._shadowMap;
  56658. };
  56659. /**
  56660. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  56661. * @returns The render target texture if the shadow map is present otherwise, null
  56662. */
  56663. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  56664. if (this._shadowMap2) {
  56665. return this._shadowMap2;
  56666. }
  56667. return this._shadowMap;
  56668. };
  56669. /**
  56670. * Helper function to add a mesh and its descendants to the list of shadow casters.
  56671. * @param mesh Mesh to add
  56672. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  56673. * @returns the Shadow Generator itself
  56674. */
  56675. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  56676. if (includeDescendants === void 0) { includeDescendants = true; }
  56677. if (!this._shadowMap) {
  56678. return this;
  56679. }
  56680. if (!this._shadowMap.renderList) {
  56681. this._shadowMap.renderList = [];
  56682. }
  56683. this._shadowMap.renderList.push(mesh);
  56684. if (includeDescendants) {
  56685. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  56686. }
  56687. return this;
  56688. var _a;
  56689. };
  56690. /**
  56691. * Helper function to remove a mesh and its descendants from the list of shadow casters
  56692. * @param mesh Mesh to remove
  56693. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  56694. * @returns the Shadow Generator itself
  56695. */
  56696. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  56697. if (includeDescendants === void 0) { includeDescendants = true; }
  56698. if (!this._shadowMap || !this._shadowMap.renderList) {
  56699. return this;
  56700. }
  56701. var index = this._shadowMap.renderList.indexOf(mesh);
  56702. if (index !== -1) {
  56703. this._shadowMap.renderList.splice(index, 1);
  56704. }
  56705. if (includeDescendants) {
  56706. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  56707. var child = _a[_i];
  56708. this.removeShadowCaster(child);
  56709. }
  56710. }
  56711. return this;
  56712. };
  56713. /**
  56714. * Returns the associated light object.
  56715. * @returns the light generating the shadow
  56716. */
  56717. ShadowGenerator.prototype.getLight = function () {
  56718. return this._light;
  56719. };
  56720. ShadowGenerator.prototype._initializeGenerator = function () {
  56721. this._light._markMeshesAsLightDirty();
  56722. this._initializeShadowMap();
  56723. };
  56724. ShadowGenerator.prototype._initializeShadowMap = function () {
  56725. var _this = this;
  56726. // Render target
  56727. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  56728. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56729. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56730. this._shadowMap.anisotropicFilteringLevel = 1;
  56731. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56732. this._shadowMap.renderParticles = false;
  56733. this._shadowMap.ignoreCameraViewport = true;
  56734. // Record Face Index before render.
  56735. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  56736. _this._currentFaceIndex = faceIndex;
  56737. });
  56738. // Custom render function.
  56739. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  56740. // Blur if required afer render.
  56741. this._shadowMap.onAfterUnbindObservable.add(function () {
  56742. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  56743. return;
  56744. }
  56745. var shadowMap = _this.getShadowMapForRendering();
  56746. if (shadowMap) {
  56747. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  56748. }
  56749. });
  56750. // Clear according to the chosen filter.
  56751. this._shadowMap.onClearObservable.add(function (engine) {
  56752. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  56753. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  56754. }
  56755. else {
  56756. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56757. }
  56758. });
  56759. };
  56760. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  56761. var _this = this;
  56762. var engine = this._scene.getEngine();
  56763. var targetSize = this._mapSize / this.blurScale;
  56764. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  56765. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  56766. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56767. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56768. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56769. }
  56770. if (this.useKernelBlur) {
  56771. 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);
  56772. this._kernelBlurXPostprocess.width = targetSize;
  56773. this._kernelBlurXPostprocess.height = targetSize;
  56774. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  56775. effect.setTexture("textureSampler", _this._shadowMap);
  56776. });
  56777. 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);
  56778. this._kernelBlurXPostprocess.autoClear = false;
  56779. this._kernelBlurYPostprocess.autoClear = false;
  56780. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56781. this._kernelBlurXPostprocess.packedFloat = true;
  56782. this._kernelBlurYPostprocess.packedFloat = true;
  56783. }
  56784. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  56785. }
  56786. else {
  56787. 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);
  56788. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  56789. effect.setFloat2("screenSize", targetSize, targetSize);
  56790. effect.setTexture("textureSampler", _this._shadowMap);
  56791. });
  56792. this._boxBlurPostprocess.autoClear = false;
  56793. this._blurPostProcesses = [this._boxBlurPostprocess];
  56794. }
  56795. };
  56796. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56797. var index;
  56798. var engine = this._scene.getEngine();
  56799. if (depthOnlySubMeshes.length) {
  56800. engine.setColorWrite(false);
  56801. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56802. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  56803. }
  56804. engine.setColorWrite(true);
  56805. }
  56806. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56807. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  56808. }
  56809. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56810. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  56811. }
  56812. if (this._transparencyShadow) {
  56813. for (index = 0; index < transparentSubMeshes.length; index++) {
  56814. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  56815. }
  56816. }
  56817. };
  56818. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  56819. var _this = this;
  56820. var mesh = subMesh.getRenderingMesh();
  56821. var scene = this._scene;
  56822. var engine = scene.getEngine();
  56823. var material = subMesh.getMaterial();
  56824. if (!material) {
  56825. return;
  56826. }
  56827. // Culling
  56828. engine.setState(material.backFaceCulling);
  56829. // Managing instances
  56830. var batch = mesh._getInstancesRenderList(subMesh._id);
  56831. if (batch.mustReturn) {
  56832. return;
  56833. }
  56834. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  56835. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  56836. engine.enableEffect(this._effect);
  56837. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  56838. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  56839. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  56840. this._effect.setVector3("lightPosition", this.getLight().position);
  56841. if (scene.activeCamera) {
  56842. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  56843. }
  56844. // Alpha test
  56845. if (material && material.needAlphaTesting()) {
  56846. var alphaTexture = material.getAlphaTestTexture();
  56847. if (alphaTexture) {
  56848. this._effect.setTexture("diffuseSampler", alphaTexture);
  56849. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  56850. }
  56851. }
  56852. // Bones
  56853. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56854. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  56855. }
  56856. if (this.forceBackFacesOnly) {
  56857. engine.setState(true, 0, false, true);
  56858. }
  56859. // Draw
  56860. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56861. if (this.forceBackFacesOnly) {
  56862. engine.setState(true, 0, false, false);
  56863. }
  56864. }
  56865. else {
  56866. // Need to reset refresh rate of the shadowMap
  56867. if (this._shadowMap) {
  56868. this._shadowMap.resetRefreshCounter();
  56869. }
  56870. }
  56871. };
  56872. ShadowGenerator.prototype._applyFilterValues = function () {
  56873. if (!this._shadowMap) {
  56874. return;
  56875. }
  56876. if (this.filter === ShadowGenerator.FILTER_NONE) {
  56877. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56878. }
  56879. else {
  56880. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56881. }
  56882. };
  56883. /**
  56884. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  56885. * @param onCompiled Callback triggered at the and of the effects compilation
  56886. * @param options Sets of optional options forcing the compilation with different modes
  56887. */
  56888. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  56889. var _this = this;
  56890. var localOptions = __assign({ useInstances: false }, options);
  56891. var shadowMap = this.getShadowMap();
  56892. if (!shadowMap) {
  56893. if (onCompiled) {
  56894. onCompiled(this);
  56895. }
  56896. return;
  56897. }
  56898. var renderList = shadowMap.renderList;
  56899. if (!renderList) {
  56900. if (onCompiled) {
  56901. onCompiled(this);
  56902. }
  56903. return;
  56904. }
  56905. var subMeshes = new Array();
  56906. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  56907. var mesh = renderList_1[_i];
  56908. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  56909. }
  56910. if (subMeshes.length === 0) {
  56911. if (onCompiled) {
  56912. onCompiled(this);
  56913. }
  56914. return;
  56915. }
  56916. var currentIndex = 0;
  56917. var checkReady = function () {
  56918. if (!_this._scene || !_this._scene.getEngine()) {
  56919. return;
  56920. }
  56921. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  56922. currentIndex++;
  56923. if (currentIndex >= subMeshes.length) {
  56924. if (onCompiled) {
  56925. onCompiled(_this);
  56926. }
  56927. return;
  56928. }
  56929. }
  56930. setTimeout(checkReady, 16);
  56931. };
  56932. checkReady();
  56933. };
  56934. /**
  56935. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  56936. * @param subMesh The submesh we want to render in the shadow map
  56937. * @param useInstances Defines wether will draw in the map using instances
  56938. * @returns true if ready otherwise, false
  56939. */
  56940. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  56941. var defines = [];
  56942. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56943. defines.push("#define FLOAT");
  56944. }
  56945. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56946. defines.push("#define ESM");
  56947. }
  56948. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56949. var mesh = subMesh.getMesh();
  56950. var material = subMesh.getMaterial();
  56951. // Alpha test
  56952. if (material && material.needAlphaTesting()) {
  56953. var alphaTexture = material.getAlphaTestTexture();
  56954. if (alphaTexture) {
  56955. defines.push("#define ALPHATEST");
  56956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56957. attribs.push(BABYLON.VertexBuffer.UVKind);
  56958. defines.push("#define UV1");
  56959. }
  56960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56961. if (alphaTexture.coordinatesIndex === 1) {
  56962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56963. defines.push("#define UV2");
  56964. }
  56965. }
  56966. }
  56967. }
  56968. // Bones
  56969. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56972. if (mesh.numBoneInfluencers > 4) {
  56973. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56974. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56975. }
  56976. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56977. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56978. }
  56979. else {
  56980. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56981. }
  56982. // Instances
  56983. if (useInstances) {
  56984. defines.push("#define INSTANCES");
  56985. attribs.push("world0");
  56986. attribs.push("world1");
  56987. attribs.push("world2");
  56988. attribs.push("world3");
  56989. }
  56990. // Get correct effect
  56991. var join = defines.join("\n");
  56992. if (this._cachedDefines !== join) {
  56993. this._cachedDefines = join;
  56994. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  56995. }
  56996. if (!this._effect.isReady()) {
  56997. return false;
  56998. }
  56999. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57000. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  57001. this._initializeBlurRTTAndPostProcesses();
  57002. }
  57003. }
  57004. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  57005. return false;
  57006. }
  57007. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  57008. return false;
  57009. }
  57010. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  57011. return false;
  57012. }
  57013. return true;
  57014. };
  57015. /**
  57016. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  57017. * @param defines Defines of the material we want to update
  57018. * @param lightIndex Index of the light in the enabled light list of the material
  57019. */
  57020. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  57021. var scene = this._scene;
  57022. var light = this._light;
  57023. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57024. return;
  57025. }
  57026. defines["SHADOW" + lightIndex] = true;
  57027. if (this.usePoissonSampling) {
  57028. defines["SHADOWPCF" + lightIndex] = true;
  57029. }
  57030. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  57031. defines["SHADOWESM" + lightIndex] = true;
  57032. }
  57033. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57034. defines["SHADOWCLOSEESM" + lightIndex] = true;
  57035. }
  57036. if (light.needCube()) {
  57037. defines["SHADOWCUBE" + lightIndex] = true;
  57038. }
  57039. };
  57040. /**
  57041. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  57042. * defined in the generator but impacting the effect).
  57043. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  57044. * @param effect The effect we are binfing the information for
  57045. */
  57046. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  57047. var light = this._light;
  57048. var scene = this._scene;
  57049. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57050. return;
  57051. }
  57052. var camera = scene.activeCamera;
  57053. if (!camera) {
  57054. return;
  57055. }
  57056. var shadowMap = this.getShadowMap();
  57057. if (!shadowMap) {
  57058. return;
  57059. }
  57060. if (!light.needCube()) {
  57061. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  57062. }
  57063. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  57064. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  57065. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  57066. };
  57067. /**
  57068. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  57069. * (eq to shadow prjection matrix * light transform matrix)
  57070. * @returns The transform matrix used to create the shadow map
  57071. */
  57072. ShadowGenerator.prototype.getTransformMatrix = function () {
  57073. var scene = this._scene;
  57074. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  57075. return this._transformMatrix;
  57076. }
  57077. this._currentRenderID = scene.getRenderId();
  57078. this._currentFaceIndexCache = this._currentFaceIndex;
  57079. var lightPosition = this._light.position;
  57080. if (this._light.computeTransformedInformation()) {
  57081. lightPosition = this._light.transformedPosition;
  57082. }
  57083. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  57084. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  57085. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  57086. }
  57087. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  57088. this._cachedPosition = lightPosition.clone();
  57089. this._cachedDirection = this._lightDirection.clone();
  57090. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  57091. var shadowMap = this.getShadowMap();
  57092. if (shadowMap) {
  57093. var renderList = shadowMap.renderList;
  57094. if (renderList) {
  57095. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  57096. }
  57097. }
  57098. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  57099. }
  57100. return this._transformMatrix;
  57101. };
  57102. /**
  57103. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  57104. * Cube and 2D textures for instance.
  57105. */
  57106. ShadowGenerator.prototype.recreateShadowMap = function () {
  57107. var shadowMap = this._shadowMap;
  57108. if (!shadowMap) {
  57109. return;
  57110. }
  57111. // Track render list.
  57112. var renderList = shadowMap.renderList;
  57113. // Clean up existing data.
  57114. this._disposeRTTandPostProcesses();
  57115. // Reinitializes.
  57116. this._initializeGenerator();
  57117. // Reaffect the filter to ensure a correct fallback if necessary.
  57118. this.filter = this.filter;
  57119. // Reaffect the filter.
  57120. this._applyFilterValues();
  57121. // Reaffect Render List.
  57122. this._shadowMap.renderList = renderList;
  57123. };
  57124. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  57125. if (this._shadowMap2) {
  57126. this._shadowMap2.dispose();
  57127. this._shadowMap2 = null;
  57128. }
  57129. if (this._boxBlurPostprocess) {
  57130. this._boxBlurPostprocess.dispose();
  57131. this._boxBlurPostprocess = null;
  57132. }
  57133. if (this._kernelBlurXPostprocess) {
  57134. this._kernelBlurXPostprocess.dispose();
  57135. this._kernelBlurXPostprocess = null;
  57136. }
  57137. if (this._kernelBlurYPostprocess) {
  57138. this._kernelBlurYPostprocess.dispose();
  57139. this._kernelBlurYPostprocess = null;
  57140. }
  57141. this._blurPostProcesses = [];
  57142. };
  57143. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  57144. if (this._shadowMap) {
  57145. this._shadowMap.dispose();
  57146. this._shadowMap = null;
  57147. }
  57148. this._disposeBlurPostProcesses();
  57149. };
  57150. /**
  57151. * Disposes the ShadowGenerator.
  57152. * Returns nothing.
  57153. */
  57154. ShadowGenerator.prototype.dispose = function () {
  57155. this._disposeRTTandPostProcesses();
  57156. if (this._light) {
  57157. this._light._shadowGenerator = null;
  57158. this._light._markMeshesAsLightDirty();
  57159. }
  57160. };
  57161. /**
  57162. * Serializes the shadow generator setup to a json object.
  57163. * @returns The serialized JSON object
  57164. */
  57165. ShadowGenerator.prototype.serialize = function () {
  57166. var serializationObject = {};
  57167. var shadowMap = this.getShadowMap();
  57168. if (!shadowMap) {
  57169. return serializationObject;
  57170. }
  57171. serializationObject.lightId = this._light.id;
  57172. serializationObject.mapSize = shadowMap.getRenderSize();
  57173. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  57174. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  57175. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57176. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57177. serializationObject.usePoissonSampling = this.usePoissonSampling;
  57178. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  57179. serializationObject.depthScale = this.depthScale;
  57180. serializationObject.darkness = this.getDarkness();
  57181. serializationObject.blurBoxOffset = this.blurBoxOffset;
  57182. serializationObject.blurKernel = this.blurKernel;
  57183. serializationObject.blurScale = this.blurScale;
  57184. serializationObject.useKernelBlur = this.useKernelBlur;
  57185. serializationObject.transparencyShadow = this._transparencyShadow;
  57186. serializationObject.renderList = [];
  57187. if (shadowMap.renderList) {
  57188. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  57189. var mesh = shadowMap.renderList[meshIndex];
  57190. serializationObject.renderList.push(mesh.id);
  57191. }
  57192. }
  57193. return serializationObject;
  57194. };
  57195. /**
  57196. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  57197. * @param parsedShadowGenerator The JSON object to parse
  57198. * @param scene The scene to create the shadow map for
  57199. * @returns The parsed shadow generator
  57200. */
  57201. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  57202. //casting to point light, as light is missing the position attr and typescript complains.
  57203. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  57204. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  57205. var shadowMap = shadowGenerator.getShadowMap();
  57206. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  57207. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  57208. meshes.forEach(function (mesh) {
  57209. if (!shadowMap) {
  57210. return;
  57211. }
  57212. if (!shadowMap.renderList) {
  57213. shadowMap.renderList = [];
  57214. }
  57215. shadowMap.renderList.push(mesh);
  57216. });
  57217. }
  57218. if (parsedShadowGenerator.usePoissonSampling) {
  57219. shadowGenerator.usePoissonSampling = true;
  57220. }
  57221. else if (parsedShadowGenerator.useExponentialShadowMap) {
  57222. shadowGenerator.useExponentialShadowMap = true;
  57223. }
  57224. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  57225. shadowGenerator.useBlurExponentialShadowMap = true;
  57226. }
  57227. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  57228. shadowGenerator.useCloseExponentialShadowMap = true;
  57229. }
  57230. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  57231. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  57232. }
  57233. else if (parsedShadowGenerator.useVarianceShadowMap) {
  57234. shadowGenerator.useExponentialShadowMap = true;
  57235. }
  57236. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  57237. shadowGenerator.useBlurExponentialShadowMap = true;
  57238. }
  57239. if (parsedShadowGenerator.depthScale) {
  57240. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  57241. }
  57242. if (parsedShadowGenerator.blurScale) {
  57243. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  57244. }
  57245. if (parsedShadowGenerator.blurBoxOffset) {
  57246. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  57247. }
  57248. if (parsedShadowGenerator.useKernelBlur) {
  57249. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  57250. }
  57251. if (parsedShadowGenerator.blurKernel) {
  57252. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  57253. }
  57254. if (parsedShadowGenerator.bias !== undefined) {
  57255. shadowGenerator.bias = parsedShadowGenerator.bias;
  57256. }
  57257. if (parsedShadowGenerator.darkness) {
  57258. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  57259. }
  57260. if (parsedShadowGenerator.transparencyShadow) {
  57261. shadowGenerator.setTransparencyShadow(true);
  57262. }
  57263. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  57264. return shadowGenerator;
  57265. };
  57266. ShadowGenerator._FILTER_NONE = 0;
  57267. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  57268. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  57269. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  57270. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  57271. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  57272. return ShadowGenerator;
  57273. }());
  57274. BABYLON.ShadowGenerator = ShadowGenerator;
  57275. })(BABYLON || (BABYLON = {}));
  57276. //# sourceMappingURL=babylon.shadowGenerator.js.map
  57277. var BABYLON;
  57278. (function (BABYLON) {
  57279. var DefaultLoadingScreen = /** @class */ (function () {
  57280. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  57281. if (_loadingText === void 0) { _loadingText = ""; }
  57282. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  57283. var _this = this;
  57284. this._renderingCanvas = _renderingCanvas;
  57285. this._loadingText = _loadingText;
  57286. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  57287. // Resize
  57288. this._resizeLoadingUI = function () {
  57289. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  57290. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  57291. if (!_this._loadingDiv) {
  57292. return;
  57293. }
  57294. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  57295. _this._loadingDiv.style.left = canvasRect.left + "px";
  57296. _this._loadingDiv.style.top = canvasRect.top + "px";
  57297. _this._loadingDiv.style.width = canvasRect.width + "px";
  57298. _this._loadingDiv.style.height = canvasRect.height + "px";
  57299. };
  57300. }
  57301. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  57302. if (this._loadingDiv) {
  57303. // Do not add a loading screen if there is already one
  57304. return;
  57305. }
  57306. this._loadingDiv = document.createElement("div");
  57307. this._loadingDiv.id = "babylonjsLoadingDiv";
  57308. this._loadingDiv.style.opacity = "0";
  57309. this._loadingDiv.style.transition = "opacity 1.5s ease";
  57310. this._loadingDiv.style.pointerEvents = "none";
  57311. // Loading text
  57312. this._loadingTextDiv = document.createElement("div");
  57313. this._loadingTextDiv.style.position = "absolute";
  57314. this._loadingTextDiv.style.left = "0";
  57315. this._loadingTextDiv.style.top = "50%";
  57316. this._loadingTextDiv.style.marginTop = "80px";
  57317. this._loadingTextDiv.style.width = "100%";
  57318. this._loadingTextDiv.style.height = "20px";
  57319. this._loadingTextDiv.style.fontFamily = "Arial";
  57320. this._loadingTextDiv.style.fontSize = "14px";
  57321. this._loadingTextDiv.style.color = "white";
  57322. this._loadingTextDiv.style.textAlign = "center";
  57323. this._loadingTextDiv.innerHTML = "Loading";
  57324. this._loadingDiv.appendChild(this._loadingTextDiv);
  57325. //set the predefined text
  57326. this._loadingTextDiv.innerHTML = this._loadingText;
  57327. // Generating keyframes
  57328. var style = document.createElement('style');
  57329. style.type = 'text/css';
  57330. 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 }";
  57331. style.innerHTML = keyFrames;
  57332. document.getElementsByTagName('head')[0].appendChild(style);
  57333. // Loading img
  57334. var imgBack = new Image();
  57335. 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";
  57336. imgBack.style.position = "absolute";
  57337. imgBack.style.left = "50%";
  57338. imgBack.style.top = "50%";
  57339. imgBack.style.marginLeft = "-60px";
  57340. imgBack.style.marginTop = "-60px";
  57341. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  57342. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  57343. imgBack.style.transformOrigin = "50% 50%";
  57344. imgBack.style.webkitTransformOrigin = "50% 50%";
  57345. this._loadingDiv.appendChild(imgBack);
  57346. this._resizeLoadingUI();
  57347. window.addEventListener("resize", this._resizeLoadingUI);
  57348. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57349. document.body.appendChild(this._loadingDiv);
  57350. this._loadingDiv.style.opacity = "1";
  57351. };
  57352. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  57353. var _this = this;
  57354. if (!this._loadingDiv) {
  57355. return;
  57356. }
  57357. var onTransitionEnd = function () {
  57358. if (!_this._loadingDiv) {
  57359. return;
  57360. }
  57361. document.body.removeChild(_this._loadingDiv);
  57362. window.removeEventListener("resize", _this._resizeLoadingUI);
  57363. _this._loadingDiv = null;
  57364. };
  57365. this._loadingDiv.style.opacity = "0";
  57366. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  57367. };
  57368. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  57369. set: function (text) {
  57370. this._loadingText = text;
  57371. if (this._loadingTextDiv) {
  57372. this._loadingTextDiv.innerHTML = this._loadingText;
  57373. }
  57374. },
  57375. enumerable: true,
  57376. configurable: true
  57377. });
  57378. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  57379. get: function () {
  57380. return this._loadingDivBackgroundColor;
  57381. },
  57382. set: function (color) {
  57383. this._loadingDivBackgroundColor = color;
  57384. if (!this._loadingDiv) {
  57385. return;
  57386. }
  57387. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57388. },
  57389. enumerable: true,
  57390. configurable: true
  57391. });
  57392. return DefaultLoadingScreen;
  57393. }());
  57394. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  57395. })(BABYLON || (BABYLON = {}));
  57396. //# sourceMappingURL=babylon.loadingScreen.js.map
  57397. var BABYLON;
  57398. (function (BABYLON) {
  57399. var SceneLoaderProgressEvent = /** @class */ (function () {
  57400. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  57401. this.lengthComputable = lengthComputable;
  57402. this.loaded = loaded;
  57403. this.total = total;
  57404. }
  57405. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  57406. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  57407. };
  57408. return SceneLoaderProgressEvent;
  57409. }());
  57410. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  57411. var SceneLoader = /** @class */ (function () {
  57412. function SceneLoader() {
  57413. }
  57414. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  57415. get: function () {
  57416. return 0;
  57417. },
  57418. enumerable: true,
  57419. configurable: true
  57420. });
  57421. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  57422. get: function () {
  57423. return 1;
  57424. },
  57425. enumerable: true,
  57426. configurable: true
  57427. });
  57428. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  57429. get: function () {
  57430. return 2;
  57431. },
  57432. enumerable: true,
  57433. configurable: true
  57434. });
  57435. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  57436. get: function () {
  57437. return 3;
  57438. },
  57439. enumerable: true,
  57440. configurable: true
  57441. });
  57442. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  57443. get: function () {
  57444. return SceneLoader._ForceFullSceneLoadingForIncremental;
  57445. },
  57446. set: function (value) {
  57447. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  57448. },
  57449. enumerable: true,
  57450. configurable: true
  57451. });
  57452. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  57453. get: function () {
  57454. return SceneLoader._ShowLoadingScreen;
  57455. },
  57456. set: function (value) {
  57457. SceneLoader._ShowLoadingScreen = value;
  57458. },
  57459. enumerable: true,
  57460. configurable: true
  57461. });
  57462. Object.defineProperty(SceneLoader, "loggingLevel", {
  57463. get: function () {
  57464. return SceneLoader._loggingLevel;
  57465. },
  57466. set: function (value) {
  57467. SceneLoader._loggingLevel = value;
  57468. },
  57469. enumerable: true,
  57470. configurable: true
  57471. });
  57472. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  57473. get: function () {
  57474. return SceneLoader._CleanBoneMatrixWeights;
  57475. },
  57476. set: function (value) {
  57477. SceneLoader._CleanBoneMatrixWeights = value;
  57478. },
  57479. enumerable: true,
  57480. configurable: true
  57481. });
  57482. SceneLoader._getDefaultPlugin = function () {
  57483. return SceneLoader._registeredPlugins[".babylon"];
  57484. };
  57485. SceneLoader._getPluginForExtension = function (extension) {
  57486. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  57487. if (registeredPlugin) {
  57488. return registeredPlugin;
  57489. }
  57490. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  57491. return SceneLoader._getDefaultPlugin();
  57492. };
  57493. SceneLoader._getPluginForDirectLoad = function (data) {
  57494. for (var extension in SceneLoader._registeredPlugins) {
  57495. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  57496. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  57497. return SceneLoader._registeredPlugins[extension];
  57498. }
  57499. }
  57500. return SceneLoader._getDefaultPlugin();
  57501. };
  57502. SceneLoader._getPluginForFilename = function (sceneFilename) {
  57503. if (sceneFilename.name) {
  57504. sceneFilename = sceneFilename.name;
  57505. }
  57506. var queryStringPosition = sceneFilename.indexOf("?");
  57507. if (queryStringPosition !== -1) {
  57508. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  57509. }
  57510. var dotPosition = sceneFilename.lastIndexOf(".");
  57511. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  57512. return SceneLoader._getPluginForExtension(extension);
  57513. };
  57514. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  57515. SceneLoader._getDirectLoad = function (sceneFilename) {
  57516. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  57517. return sceneFilename.substr(5);
  57518. }
  57519. return null;
  57520. };
  57521. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  57522. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  57523. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  57524. var plugin;
  57525. if (registeredPlugin.plugin.createPlugin) {
  57526. plugin = registeredPlugin.plugin.createPlugin();
  57527. }
  57528. else {
  57529. plugin = registeredPlugin.plugin;
  57530. }
  57531. var useArrayBuffer = registeredPlugin.isBinary;
  57532. var database;
  57533. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  57534. var dataCallback = function (data, responseURL) {
  57535. if (scene.isDisposed) {
  57536. onError("Scene has been disposed");
  57537. return;
  57538. }
  57539. scene.database = database;
  57540. onSuccess(plugin, data, responseURL);
  57541. };
  57542. var request = null;
  57543. var pluginDisposed = false;
  57544. var onDisposeObservable = plugin.onDisposeObservable;
  57545. if (onDisposeObservable) {
  57546. onDisposeObservable.add(function () {
  57547. pluginDisposed = true;
  57548. if (request) {
  57549. request.abort();
  57550. request = null;
  57551. }
  57552. onDispose();
  57553. });
  57554. }
  57555. var manifestChecked = function () {
  57556. if (pluginDisposed) {
  57557. return;
  57558. }
  57559. var url = rootUrl + sceneFilename;
  57560. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  57561. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  57562. } : undefined, database, useArrayBuffer, function (request, exception) {
  57563. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  57564. });
  57565. };
  57566. if (directLoad) {
  57567. dataCallback(directLoad);
  57568. return plugin;
  57569. }
  57570. if (rootUrl.indexOf("file:") === -1) {
  57571. if (scene.getEngine().enableOfflineSupport) {
  57572. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  57573. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  57574. }
  57575. else {
  57576. manifestChecked();
  57577. }
  57578. }
  57579. else {
  57580. var fileOrString = sceneFilename;
  57581. if (fileOrString.name) {
  57582. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  57583. }
  57584. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  57585. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  57586. }
  57587. else {
  57588. onError("Unable to find file named " + sceneFilename);
  57589. }
  57590. }
  57591. return plugin;
  57592. };
  57593. // Public functions
  57594. SceneLoader.GetPluginForExtension = function (extension) {
  57595. return SceneLoader._getPluginForExtension(extension).plugin;
  57596. };
  57597. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  57598. return !!SceneLoader._registeredPlugins[extension];
  57599. };
  57600. SceneLoader.RegisterPlugin = function (plugin) {
  57601. if (typeof plugin.extensions === "string") {
  57602. var extension = plugin.extensions;
  57603. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57604. plugin: plugin,
  57605. isBinary: false
  57606. };
  57607. }
  57608. else {
  57609. var extensions = plugin.extensions;
  57610. Object.keys(extensions).forEach(function (extension) {
  57611. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57612. plugin: plugin,
  57613. isBinary: extensions[extension].isBinary
  57614. };
  57615. });
  57616. }
  57617. };
  57618. /**
  57619. * Import meshes into a scene
  57620. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  57621. * @param rootUrl a string that defines the root url for scene and resources
  57622. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57623. * @param scene the instance of BABYLON.Scene to append to
  57624. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  57625. * @param onProgress a callback with a progress event for each file being loaded
  57626. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57627. */
  57628. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57629. if (onSuccess === void 0) { onSuccess = null; }
  57630. if (onProgress === void 0) { onProgress = null; }
  57631. if (onError === void 0) { onError = null; }
  57632. if (pluginExtension === void 0) { pluginExtension = null; }
  57633. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57634. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57635. return null;
  57636. }
  57637. var loadingToken = {};
  57638. scene._addPendingData(loadingToken);
  57639. var disposeHandler = function () {
  57640. scene._removePendingData(loadingToken);
  57641. };
  57642. var errorHandler = function (message, exception) {
  57643. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  57644. if (onError) {
  57645. onError(scene, errorMessage, exception);
  57646. }
  57647. else {
  57648. BABYLON.Tools.Error(errorMessage);
  57649. // should the exception be thrown?
  57650. }
  57651. disposeHandler();
  57652. };
  57653. var progressHandler = onProgress ? function (event) {
  57654. try {
  57655. onProgress(event);
  57656. }
  57657. catch (e) {
  57658. errorHandler("Error in onProgress callback", e);
  57659. }
  57660. } : undefined;
  57661. var successHandler = function (meshes, particleSystems, skeletons) {
  57662. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  57663. if (onSuccess) {
  57664. try {
  57665. onSuccess(meshes, particleSystems, skeletons);
  57666. }
  57667. catch (e) {
  57668. errorHandler("Error in onSuccess callback", e);
  57669. }
  57670. }
  57671. scene._removePendingData(loadingToken);
  57672. };
  57673. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57674. if (plugin.rewriteRootURL) {
  57675. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  57676. }
  57677. if (plugin.importMesh) {
  57678. var syncedPlugin = plugin;
  57679. var meshes = new Array();
  57680. var particleSystems = new Array();
  57681. var skeletons = new Array();
  57682. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  57683. return;
  57684. }
  57685. scene.loadingPluginName = plugin.name;
  57686. successHandler(meshes, particleSystems, skeletons);
  57687. }
  57688. else {
  57689. var asyncedPlugin = plugin;
  57690. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  57691. scene.loadingPluginName = plugin.name;
  57692. successHandler(meshes, particleSystems, skeletons);
  57693. }, progressHandler, errorHandler);
  57694. }
  57695. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57696. };
  57697. /**
  57698. * Load a scene
  57699. * @param rootUrl a string that defines the root url for scene and resources
  57700. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57701. * @param engine is the instance of BABYLON.Engine to use to create the scene
  57702. * @param onSuccess a callback with the scene when import succeeds
  57703. * @param onProgress a callback with a progress event for each file being loaded
  57704. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57705. */
  57706. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  57707. if (onSuccess === void 0) { onSuccess = null; }
  57708. if (onProgress === void 0) { onProgress = null; }
  57709. if (onError === void 0) { onError = null; }
  57710. if (pluginExtension === void 0) { pluginExtension = null; }
  57711. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  57712. };
  57713. /**
  57714. * Append a scene
  57715. * @param rootUrl a string that defines the root url for scene and resources
  57716. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57717. * @param scene is the instance of BABYLON.Scene to append to
  57718. * @param onSuccess a callback with the scene when import succeeds
  57719. * @param onProgress a callback with a progress event for each file being loaded
  57720. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57721. */
  57722. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57723. if (onSuccess === void 0) { onSuccess = null; }
  57724. if (onProgress === void 0) { onProgress = null; }
  57725. if (onError === void 0) { onError = null; }
  57726. if (pluginExtension === void 0) { pluginExtension = null; }
  57727. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57728. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57729. return null;
  57730. }
  57731. if (SceneLoader.ShowLoadingScreen) {
  57732. scene.getEngine().displayLoadingUI();
  57733. }
  57734. var loadingToken = {};
  57735. scene._addPendingData(loadingToken);
  57736. var disposeHandler = function () {
  57737. scene._removePendingData(loadingToken);
  57738. scene.getEngine().hideLoadingUI();
  57739. };
  57740. var errorHandler = function (message, exception) {
  57741. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57742. if (onError) {
  57743. onError(scene, errorMessage, exception);
  57744. }
  57745. else {
  57746. BABYLON.Tools.Error(errorMessage);
  57747. // should the exception be thrown?
  57748. }
  57749. disposeHandler();
  57750. };
  57751. var progressHandler = onProgress ? function (event) {
  57752. try {
  57753. onProgress(event);
  57754. }
  57755. catch (e) {
  57756. errorHandler("Error in onProgress callback", e);
  57757. }
  57758. } : undefined;
  57759. var successHandler = function () {
  57760. if (onSuccess) {
  57761. try {
  57762. onSuccess(scene);
  57763. }
  57764. catch (e) {
  57765. errorHandler("Error in onSuccess callback", e);
  57766. }
  57767. }
  57768. scene._removePendingData(loadingToken);
  57769. };
  57770. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57771. if (plugin.load) {
  57772. var syncedPlugin = plugin;
  57773. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  57774. return;
  57775. }
  57776. scene.loadingPluginName = plugin.name;
  57777. successHandler();
  57778. }
  57779. else {
  57780. var asyncedPlugin = plugin;
  57781. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  57782. scene.loadingPluginName = plugin.name;
  57783. successHandler();
  57784. }, progressHandler, errorHandler);
  57785. }
  57786. if (SceneLoader.ShowLoadingScreen) {
  57787. scene.executeWhenReady(function () {
  57788. scene.getEngine().hideLoadingUI();
  57789. });
  57790. }
  57791. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57792. };
  57793. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57794. if (onSuccess === void 0) { onSuccess = null; }
  57795. if (onProgress === void 0) { onProgress = null; }
  57796. if (onError === void 0) { onError = null; }
  57797. if (pluginExtension === void 0) { pluginExtension = null; }
  57798. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57799. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57800. return null;
  57801. }
  57802. var loadingToken = {};
  57803. scene._addPendingData(loadingToken);
  57804. var disposeHandler = function () {
  57805. scene._removePendingData(loadingToken);
  57806. };
  57807. var errorHandler = function (message, exception) {
  57808. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57809. if (onError) {
  57810. onError(scene, errorMessage, exception);
  57811. }
  57812. else {
  57813. BABYLON.Tools.Error(errorMessage);
  57814. // should the exception be thrown?
  57815. }
  57816. disposeHandler();
  57817. };
  57818. var progressHandler = onProgress ? function (event) {
  57819. try {
  57820. onProgress(event);
  57821. }
  57822. catch (e) {
  57823. errorHandler("Error in onProgress callback", e);
  57824. }
  57825. } : undefined;
  57826. var successHandler = function (assets) {
  57827. if (onSuccess) {
  57828. try {
  57829. onSuccess(assets);
  57830. }
  57831. catch (e) {
  57832. errorHandler("Error in onSuccess callback", e);
  57833. }
  57834. }
  57835. scene._removePendingData(loadingToken);
  57836. };
  57837. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57838. if (plugin.loadAssets) {
  57839. var syncedPlugin = plugin;
  57840. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  57841. if (!assetContainer) {
  57842. return;
  57843. }
  57844. scene.loadingPluginName = plugin.name;
  57845. successHandler(assetContainer);
  57846. }
  57847. else if (plugin.loadAssetsAsync) {
  57848. var asyncedPlugin = plugin;
  57849. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  57850. if (assetContainer) {
  57851. scene.loadingPluginName = plugin.name;
  57852. successHandler(assetContainer);
  57853. }
  57854. }, progressHandler, errorHandler);
  57855. }
  57856. else {
  57857. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  57858. }
  57859. if (SceneLoader.ShowLoadingScreen) {
  57860. scene.executeWhenReady(function () {
  57861. scene.getEngine().hideLoadingUI();
  57862. });
  57863. }
  57864. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57865. };
  57866. // Flags
  57867. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  57868. SceneLoader._ShowLoadingScreen = true;
  57869. SceneLoader._CleanBoneMatrixWeights = false;
  57870. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  57871. // Members
  57872. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  57873. SceneLoader._registeredPlugins = {};
  57874. return SceneLoader;
  57875. }());
  57876. BABYLON.SceneLoader = SceneLoader;
  57877. ;
  57878. })(BABYLON || (BABYLON = {}));
  57879. //# sourceMappingURL=babylon.sceneLoader.js.map
  57880. var BABYLON;
  57881. (function (BABYLON) {
  57882. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  57883. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57884. var parsedMaterial = parsedData.materials[index];
  57885. if (parsedMaterial.id === id) {
  57886. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57887. }
  57888. }
  57889. return null;
  57890. };
  57891. var isDescendantOf = function (mesh, names, hierarchyIds) {
  57892. for (var i in names) {
  57893. if (mesh.name === names[i]) {
  57894. hierarchyIds.push(mesh.id);
  57895. return true;
  57896. }
  57897. }
  57898. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  57899. hierarchyIds.push(mesh.id);
  57900. return true;
  57901. }
  57902. return false;
  57903. };
  57904. var logOperation = function (operation, producer) {
  57905. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  57906. };
  57907. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  57908. if (addToScene === void 0) { addToScene = false; }
  57909. var container = new BABYLON.AssetContainer(scene);
  57910. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57911. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57912. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57913. // and avoid problems with multiple concurrent .babylon loads.
  57914. var log = "importScene has failed JSON parse";
  57915. try {
  57916. var parsedData = JSON.parse(data);
  57917. log = "";
  57918. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57919. var index;
  57920. var cache;
  57921. // Lights
  57922. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  57923. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  57924. var parsedLight = parsedData.lights[index];
  57925. var light = BABYLON.Light.Parse(parsedLight, scene);
  57926. if (light) {
  57927. container.lights.push(light);
  57928. log += (index === 0 ? "\n\tLights:" : "");
  57929. log += "\n\t\t" + light.toString(fullDetails);
  57930. }
  57931. }
  57932. }
  57933. // Animations
  57934. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  57935. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  57936. var parsedAnimation = parsedData.animations[index];
  57937. var animation = BABYLON.Animation.Parse(parsedAnimation);
  57938. scene.animations.push(animation);
  57939. container.animations.push(animation);
  57940. log += (index === 0 ? "\n\tAnimations:" : "");
  57941. log += "\n\t\t" + animation.toString(fullDetails);
  57942. }
  57943. }
  57944. // Materials
  57945. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  57946. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57947. var parsedMaterial = parsedData.materials[index];
  57948. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57949. container.materials.push(mat);
  57950. log += (index === 0 ? "\n\tMaterials:" : "");
  57951. log += "\n\t\t" + mat.toString(fullDetails);
  57952. }
  57953. }
  57954. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57955. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  57956. var parsedMultiMaterial = parsedData.multiMaterials[index];
  57957. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57958. container.multiMaterials.push(mmat);
  57959. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  57960. log += "\n\t\t" + mmat.toString(fullDetails);
  57961. }
  57962. }
  57963. // Morph targets
  57964. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  57965. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  57966. var managerData = _a[_i];
  57967. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  57968. }
  57969. }
  57970. // Skeletons
  57971. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57972. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  57973. var parsedSkeleton = parsedData.skeletons[index];
  57974. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57975. container.skeletons.push(skeleton);
  57976. log += (index === 0 ? "\n\tSkeletons:" : "");
  57977. log += "\n\t\t" + skeleton.toString(fullDetails);
  57978. }
  57979. }
  57980. // Geometries
  57981. var geometries = parsedData.geometries;
  57982. if (geometries !== undefined && geometries !== null) {
  57983. var addedGeometry = new Array();
  57984. // Boxes
  57985. var boxes = geometries.boxes;
  57986. if (boxes !== undefined && boxes !== null) {
  57987. for (index = 0, cache = boxes.length; index < cache; index++) {
  57988. var parsedBox = boxes[index];
  57989. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  57990. }
  57991. }
  57992. // Spheres
  57993. var spheres = geometries.spheres;
  57994. if (spheres !== undefined && spheres !== null) {
  57995. for (index = 0, cache = spheres.length; index < cache; index++) {
  57996. var parsedSphere = spheres[index];
  57997. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  57998. }
  57999. }
  58000. // Cylinders
  58001. var cylinders = geometries.cylinders;
  58002. if (cylinders !== undefined && cylinders !== null) {
  58003. for (index = 0, cache = cylinders.length; index < cache; index++) {
  58004. var parsedCylinder = cylinders[index];
  58005. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  58006. }
  58007. }
  58008. // Toruses
  58009. var toruses = geometries.toruses;
  58010. if (toruses !== undefined && toruses !== null) {
  58011. for (index = 0, cache = toruses.length; index < cache; index++) {
  58012. var parsedTorus = toruses[index];
  58013. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  58014. }
  58015. }
  58016. // Grounds
  58017. var grounds = geometries.grounds;
  58018. if (grounds !== undefined && grounds !== null) {
  58019. for (index = 0, cache = grounds.length; index < cache; index++) {
  58020. var parsedGround = grounds[index];
  58021. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  58022. }
  58023. }
  58024. // Planes
  58025. var planes = geometries.planes;
  58026. if (planes !== undefined && planes !== null) {
  58027. for (index = 0, cache = planes.length; index < cache; index++) {
  58028. var parsedPlane = planes[index];
  58029. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  58030. }
  58031. }
  58032. // TorusKnots
  58033. var torusKnots = geometries.torusKnots;
  58034. if (torusKnots !== undefined && torusKnots !== null) {
  58035. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  58036. var parsedTorusKnot = torusKnots[index];
  58037. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  58038. }
  58039. }
  58040. // VertexData
  58041. var vertexData = geometries.vertexData;
  58042. if (vertexData !== undefined && vertexData !== null) {
  58043. for (index = 0, cache = vertexData.length; index < cache; index++) {
  58044. var parsedVertexData = vertexData[index];
  58045. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  58046. }
  58047. }
  58048. addedGeometry.forEach(function (g) {
  58049. if (g) {
  58050. container.geometries.push(g);
  58051. }
  58052. });
  58053. }
  58054. // Transform nodes
  58055. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  58056. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  58057. var parsedTransformNode = parsedData.transformNodes[index];
  58058. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  58059. container.transformNodes.push(node);
  58060. }
  58061. }
  58062. // Meshes
  58063. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58064. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58065. var parsedMesh = parsedData.meshes[index];
  58066. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58067. container.meshes.push(mesh);
  58068. log += (index === 0 ? "\n\tMeshes:" : "");
  58069. log += "\n\t\t" + mesh.toString(fullDetails);
  58070. }
  58071. }
  58072. // Cameras
  58073. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  58074. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  58075. var parsedCamera = parsedData.cameras[index];
  58076. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  58077. container.cameras.push(camera);
  58078. log += (index === 0 ? "\n\tCameras:" : "");
  58079. log += "\n\t\t" + camera.toString(fullDetails);
  58080. }
  58081. }
  58082. // Browsing all the graph to connect the dots
  58083. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  58084. var camera = scene.cameras[index];
  58085. if (camera._waitingParentId) {
  58086. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  58087. camera._waitingParentId = null;
  58088. }
  58089. }
  58090. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58091. var light_1 = scene.lights[index];
  58092. if (light_1 && light_1._waitingParentId) {
  58093. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  58094. light_1._waitingParentId = null;
  58095. }
  58096. }
  58097. // Sounds
  58098. // TODO: add sound
  58099. var loadedSounds = [];
  58100. var loadedSound;
  58101. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  58102. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  58103. var parsedSound = parsedData.sounds[index];
  58104. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58105. if (!parsedSound.url)
  58106. parsedSound.url = parsedSound.name;
  58107. if (!loadedSounds[parsedSound.url]) {
  58108. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  58109. loadedSounds[parsedSound.url] = loadedSound;
  58110. container.sounds.push(loadedSound);
  58111. }
  58112. else {
  58113. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  58114. }
  58115. }
  58116. else {
  58117. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  58118. }
  58119. }
  58120. }
  58121. loadedSounds = [];
  58122. // Connect parents & children and parse actions
  58123. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  58124. var transformNode = scene.transformNodes[index];
  58125. if (transformNode._waitingParentId) {
  58126. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  58127. transformNode._waitingParentId = null;
  58128. }
  58129. }
  58130. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58131. var mesh = scene.meshes[index];
  58132. if (mesh._waitingParentId) {
  58133. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  58134. mesh._waitingParentId = null;
  58135. }
  58136. if (mesh._waitingActions) {
  58137. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  58138. mesh._waitingActions = null;
  58139. }
  58140. }
  58141. // freeze world matrix application
  58142. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58143. var currentMesh = scene.meshes[index];
  58144. if (currentMesh._waitingFreezeWorldMatrix) {
  58145. currentMesh.freezeWorldMatrix();
  58146. currentMesh._waitingFreezeWorldMatrix = null;
  58147. }
  58148. else {
  58149. currentMesh.computeWorldMatrix(true);
  58150. }
  58151. }
  58152. // Particles Systems
  58153. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58154. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58155. var parsedParticleSystem = parsedData.particleSystems[index];
  58156. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58157. container.particleSystems.push(ps);
  58158. }
  58159. }
  58160. // Lens flares
  58161. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  58162. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  58163. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  58164. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  58165. container.lensFlareSystems.push(lf);
  58166. }
  58167. }
  58168. // Shadows
  58169. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  58170. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  58171. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  58172. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  58173. container.shadowGenerators.push(sg);
  58174. }
  58175. }
  58176. // Lights exclusions / inclusions
  58177. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58178. var light_2 = scene.lights[index];
  58179. // Excluded check
  58180. if (light_2._excludedMeshesIds.length > 0) {
  58181. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  58182. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  58183. if (excludedMesh) {
  58184. light_2.excludedMeshes.push(excludedMesh);
  58185. }
  58186. }
  58187. light_2._excludedMeshesIds = [];
  58188. }
  58189. // Included check
  58190. if (light_2._includedOnlyMeshesIds.length > 0) {
  58191. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  58192. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  58193. if (includedOnlyMesh) {
  58194. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  58195. }
  58196. }
  58197. light_2._includedOnlyMeshesIds = [];
  58198. }
  58199. }
  58200. // Actions (scene)
  58201. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  58202. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  58203. }
  58204. if (!addToScene) {
  58205. container.removeAllFromScene();
  58206. }
  58207. return container;
  58208. }
  58209. catch (err) {
  58210. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  58211. if (onError) {
  58212. onError(msg, err);
  58213. }
  58214. else {
  58215. BABYLON.Tools.Log(msg);
  58216. throw err;
  58217. }
  58218. }
  58219. finally {
  58220. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58221. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58222. }
  58223. }
  58224. return null;
  58225. };
  58226. BABYLON.SceneLoader.RegisterPlugin({
  58227. name: "babylon.js",
  58228. extensions: ".babylon",
  58229. canDirectLoad: function (data) {
  58230. if (data.indexOf("babylon") !== -1) {
  58231. return true;
  58232. }
  58233. return false;
  58234. },
  58235. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  58236. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58237. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58238. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58239. // and avoid problems with multiple concurrent .babylon loads.
  58240. var log = "importMesh has failed JSON parse";
  58241. try {
  58242. var parsedData = JSON.parse(data);
  58243. log = "";
  58244. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58245. if (!meshesNames) {
  58246. meshesNames = null;
  58247. }
  58248. else if (!Array.isArray(meshesNames)) {
  58249. meshesNames = [meshesNames];
  58250. }
  58251. var hierarchyIds = new Array();
  58252. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58253. var loadedSkeletonsIds = [];
  58254. var loadedMaterialsIds = [];
  58255. var index;
  58256. var cache;
  58257. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58258. var parsedMesh = parsedData.meshes[index];
  58259. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  58260. if (meshesNames !== null) {
  58261. // Remove found mesh name from list.
  58262. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  58263. }
  58264. //Geometry?
  58265. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  58266. //does the file contain geometries?
  58267. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  58268. //find the correct geometry and add it to the scene
  58269. var found = false;
  58270. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  58271. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  58272. return;
  58273. }
  58274. else {
  58275. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  58276. if (parsedGeometryData.id === parsedMesh.geometryId) {
  58277. switch (geometryType) {
  58278. case "boxes":
  58279. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  58280. break;
  58281. case "spheres":
  58282. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  58283. break;
  58284. case "cylinders":
  58285. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  58286. break;
  58287. case "toruses":
  58288. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  58289. break;
  58290. case "grounds":
  58291. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  58292. break;
  58293. case "planes":
  58294. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  58295. break;
  58296. case "torusKnots":
  58297. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  58298. break;
  58299. case "vertexData":
  58300. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  58301. break;
  58302. }
  58303. found = true;
  58304. }
  58305. });
  58306. }
  58307. });
  58308. if (found === false) {
  58309. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  58310. }
  58311. }
  58312. }
  58313. // Material ?
  58314. if (parsedMesh.materialId) {
  58315. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  58316. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58317. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  58318. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  58319. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  58320. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  58321. var subMatId = parsedMultiMaterial.materials[matIndex];
  58322. loadedMaterialsIds.push(subMatId);
  58323. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  58324. log += "\n\tMaterial " + mat.toString(fullDetails);
  58325. }
  58326. loadedMaterialsIds.push(parsedMultiMaterial.id);
  58327. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58328. materialFound = true;
  58329. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  58330. break;
  58331. }
  58332. }
  58333. }
  58334. if (materialFound === false) {
  58335. loadedMaterialsIds.push(parsedMesh.materialId);
  58336. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  58337. if (!mat) {
  58338. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  58339. }
  58340. else {
  58341. log += "\n\tMaterial " + mat.toString(fullDetails);
  58342. }
  58343. }
  58344. }
  58345. // Skeleton ?
  58346. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58347. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  58348. if (skeletonAlreadyLoaded === false) {
  58349. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  58350. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  58351. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  58352. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58353. skeletons.push(skeleton);
  58354. loadedSkeletonsIds.push(parsedSkeleton.id);
  58355. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  58356. }
  58357. }
  58358. }
  58359. }
  58360. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58361. meshes.push(mesh);
  58362. log += "\n\tMesh " + mesh.toString(fullDetails);
  58363. }
  58364. }
  58365. // Connecting parents
  58366. var currentMesh;
  58367. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58368. currentMesh = scene.meshes[index];
  58369. if (currentMesh._waitingParentId) {
  58370. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  58371. currentMesh._waitingParentId = null;
  58372. }
  58373. }
  58374. // freeze and compute world matrix application
  58375. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58376. currentMesh = scene.meshes[index];
  58377. if (currentMesh._waitingFreezeWorldMatrix) {
  58378. currentMesh.freezeWorldMatrix();
  58379. currentMesh._waitingFreezeWorldMatrix = null;
  58380. }
  58381. else {
  58382. currentMesh.computeWorldMatrix(true);
  58383. }
  58384. }
  58385. }
  58386. // Particles
  58387. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58388. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58389. var parsedParticleSystem = parsedData.particleSystems[index];
  58390. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  58391. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  58392. }
  58393. }
  58394. }
  58395. return true;
  58396. }
  58397. catch (err) {
  58398. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  58399. if (onError) {
  58400. onError(msg, err);
  58401. }
  58402. else {
  58403. BABYLON.Tools.Log(msg);
  58404. throw err;
  58405. }
  58406. }
  58407. finally {
  58408. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58409. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58410. }
  58411. }
  58412. return false;
  58413. },
  58414. load: function (scene, data, rootUrl, onError) {
  58415. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58416. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58417. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58418. // and avoid problems with multiple concurrent .babylon loads.
  58419. var log = "importScene has failed JSON parse";
  58420. try {
  58421. var parsedData = JSON.parse(data);
  58422. log = "";
  58423. // Scene
  58424. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  58425. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  58426. }
  58427. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  58428. scene.autoClear = parsedData.autoClear;
  58429. }
  58430. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  58431. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  58432. }
  58433. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  58434. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  58435. }
  58436. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  58437. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  58438. }
  58439. // Fog
  58440. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  58441. scene.fogMode = parsedData.fogMode;
  58442. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  58443. scene.fogStart = parsedData.fogStart;
  58444. scene.fogEnd = parsedData.fogEnd;
  58445. scene.fogDensity = parsedData.fogDensity;
  58446. log += "\tFog mode for scene: ";
  58447. switch (scene.fogMode) {
  58448. // getters not compiling, so using hardcoded
  58449. case 1:
  58450. log += "exp\n";
  58451. break;
  58452. case 2:
  58453. log += "exp2\n";
  58454. break;
  58455. case 3:
  58456. log += "linear\n";
  58457. break;
  58458. }
  58459. }
  58460. //Physics
  58461. if (parsedData.physicsEnabled) {
  58462. var physicsPlugin;
  58463. if (parsedData.physicsEngine === "cannon") {
  58464. physicsPlugin = new BABYLON.CannonJSPlugin();
  58465. }
  58466. else if (parsedData.physicsEngine === "oimo") {
  58467. physicsPlugin = new BABYLON.OimoJSPlugin();
  58468. }
  58469. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  58470. //else - default engine, which is currently oimo
  58471. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  58472. scene.enablePhysics(physicsGravity, physicsPlugin);
  58473. }
  58474. // Metadata
  58475. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  58476. scene.metadata = parsedData.metadata;
  58477. }
  58478. //collisions, if defined. otherwise, default is true
  58479. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  58480. scene.collisionsEnabled = parsedData.collisionsEnabled;
  58481. }
  58482. scene.workerCollisions = !!parsedData.workerCollisions;
  58483. var container = loadAssets(scene, data, rootUrl, onerror, true);
  58484. if (!container) {
  58485. return false;
  58486. }
  58487. if (parsedData.autoAnimate) {
  58488. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  58489. }
  58490. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  58491. scene.setActiveCameraByID(parsedData.activeCameraID);
  58492. }
  58493. // Environment texture
  58494. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  58495. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  58496. if (parsedData.createDefaultSkybox === true) {
  58497. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  58498. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  58499. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  58500. }
  58501. }
  58502. // Finish
  58503. return true;
  58504. }
  58505. catch (err) {
  58506. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  58507. if (onError) {
  58508. onError(msg, err);
  58509. }
  58510. else {
  58511. BABYLON.Tools.Log(msg);
  58512. throw err;
  58513. }
  58514. }
  58515. finally {
  58516. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58517. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58518. }
  58519. }
  58520. return false;
  58521. },
  58522. loadAssets: function (scene, data, rootUrl, onError) {
  58523. var container = loadAssets(scene, data, rootUrl, onerror);
  58524. return container;
  58525. }
  58526. });
  58527. })(BABYLON || (BABYLON = {}));
  58528. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  58529. var BABYLON;
  58530. (function (BABYLON) {
  58531. var FilesInput = /** @class */ (function () {
  58532. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  58533. this.onProcessFileCallback = function () { return true; };
  58534. this._engine = engine;
  58535. this._currentScene = scene;
  58536. this._sceneLoadedCallback = sceneLoadedCallback;
  58537. this._progressCallback = progressCallback;
  58538. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58539. this._textureLoadingCallback = textureLoadingCallback;
  58540. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  58541. this._onReloadCallback = onReloadCallback;
  58542. this._errorCallback = errorCallback;
  58543. }
  58544. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  58545. var _this = this;
  58546. if (elementToMonitor) {
  58547. this._elementToMonitor = elementToMonitor;
  58548. this._dragEnterHandler = function (e) { _this.drag(e); };
  58549. this._dragOverHandler = function (e) { _this.drag(e); };
  58550. this._dropHandler = function (e) { _this.drop(e); };
  58551. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  58552. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  58553. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  58554. }
  58555. };
  58556. FilesInput.prototype.dispose = function () {
  58557. if (!this._elementToMonitor) {
  58558. return;
  58559. }
  58560. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  58561. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  58562. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  58563. };
  58564. FilesInput.prototype.renderFunction = function () {
  58565. if (this._additionalRenderLoopLogicCallback) {
  58566. this._additionalRenderLoopLogicCallback();
  58567. }
  58568. if (this._currentScene) {
  58569. if (this._textureLoadingCallback) {
  58570. var remaining = this._currentScene.getWaitingItemsCount();
  58571. if (remaining > 0) {
  58572. this._textureLoadingCallback(remaining);
  58573. }
  58574. }
  58575. this._currentScene.render();
  58576. }
  58577. };
  58578. FilesInput.prototype.drag = function (e) {
  58579. e.stopPropagation();
  58580. e.preventDefault();
  58581. };
  58582. FilesInput.prototype.drop = function (eventDrop) {
  58583. eventDrop.stopPropagation();
  58584. eventDrop.preventDefault();
  58585. this.loadFiles(eventDrop);
  58586. };
  58587. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  58588. var _this = this;
  58589. var reader = folder.createReader();
  58590. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  58591. reader.readEntries(function (entries) {
  58592. remaining.count += entries.length;
  58593. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  58594. var entry = entries_1[_i];
  58595. if (entry.isFile) {
  58596. entry.file(function (file) {
  58597. file.correctName = relativePath + file.name;
  58598. files.push(file);
  58599. if (--remaining.count === 0) {
  58600. callback();
  58601. }
  58602. });
  58603. }
  58604. else if (entry.isDirectory) {
  58605. _this._traverseFolder(entry, files, remaining, callback);
  58606. }
  58607. }
  58608. if (--remaining.count) {
  58609. callback();
  58610. }
  58611. });
  58612. };
  58613. FilesInput.prototype._processFiles = function (files) {
  58614. for (var i = 0; i < files.length; i++) {
  58615. var name = files[i].correctName.toLowerCase();
  58616. var extension = name.split('.').pop();
  58617. if (!this.onProcessFileCallback(files[i], name, extension)) {
  58618. continue;
  58619. }
  58620. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  58621. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  58622. this._sceneFileToLoad = files[i];
  58623. }
  58624. else {
  58625. FilesInput.FilesToLoad[name] = files[i];
  58626. }
  58627. }
  58628. };
  58629. FilesInput.prototype.loadFiles = function (event) {
  58630. var _this = this;
  58631. if (this._startingProcessingFilesCallback)
  58632. this._startingProcessingFilesCallback();
  58633. // Handling data transfer via drag'n'drop
  58634. if (event && event.dataTransfer && event.dataTransfer.files) {
  58635. this._filesToLoad = event.dataTransfer.files;
  58636. }
  58637. // Handling files from input files
  58638. if (event && event.target && event.target.files) {
  58639. this._filesToLoad = event.target.files;
  58640. }
  58641. if (this._filesToLoad && this._filesToLoad.length > 0) {
  58642. var files_1 = new Array();
  58643. var folders = [];
  58644. var items = event.dataTransfer ? event.dataTransfer.items : null;
  58645. for (var i = 0; i < this._filesToLoad.length; i++) {
  58646. var fileToLoad = this._filesToLoad[i];
  58647. var name_1 = fileToLoad.name.toLowerCase();
  58648. var entry = void 0;
  58649. fileToLoad.correctName = name_1;
  58650. if (items) {
  58651. var item = items[i];
  58652. if (item.getAsEntry) {
  58653. entry = item.getAsEntry();
  58654. }
  58655. else if (item.webkitGetAsEntry) {
  58656. entry = item.webkitGetAsEntry();
  58657. }
  58658. }
  58659. if (!entry) {
  58660. files_1.push(fileToLoad);
  58661. }
  58662. else {
  58663. if (entry.isDirectory) {
  58664. folders.push(entry);
  58665. }
  58666. else {
  58667. files_1.push(fileToLoad);
  58668. }
  58669. }
  58670. }
  58671. if (folders.length === 0) {
  58672. this._processFiles(files_1);
  58673. this._processReload();
  58674. }
  58675. else {
  58676. var remaining = { count: folders.length };
  58677. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  58678. var folder = folders_1[_i];
  58679. this._traverseFolder(folder, files_1, remaining, function () {
  58680. _this._processFiles(files_1);
  58681. if (remaining.count === 0) {
  58682. _this._processReload();
  58683. }
  58684. });
  58685. }
  58686. }
  58687. }
  58688. };
  58689. FilesInput.prototype._processReload = function () {
  58690. if (this._onReloadCallback) {
  58691. this._onReloadCallback(this._sceneFileToLoad);
  58692. }
  58693. else {
  58694. this.reload();
  58695. }
  58696. };
  58697. FilesInput.prototype.reload = function () {
  58698. var _this = this;
  58699. // If a scene file has been provided
  58700. if (this._sceneFileToLoad) {
  58701. if (this._currentScene) {
  58702. if (BABYLON.Tools.errorsCount > 0) {
  58703. BABYLON.Tools.ClearLogCache();
  58704. }
  58705. this._engine.stopRenderLoop();
  58706. this._currentScene.dispose();
  58707. }
  58708. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  58709. _this._currentScene = newScene;
  58710. if (_this._sceneLoadedCallback) {
  58711. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  58712. }
  58713. // Wait for textures and shaders to be ready
  58714. _this._currentScene.executeWhenReady(function () {
  58715. _this._engine.runRenderLoop(function () {
  58716. _this.renderFunction();
  58717. });
  58718. });
  58719. }, function (progress) {
  58720. if (_this._progressCallback) {
  58721. _this._progressCallback(progress);
  58722. }
  58723. }, function (scene, message) {
  58724. _this._currentScene = scene;
  58725. if (_this._errorCallback) {
  58726. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  58727. }
  58728. });
  58729. }
  58730. else {
  58731. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  58732. }
  58733. };
  58734. FilesInput.FilesToLoad = {};
  58735. return FilesInput;
  58736. }());
  58737. BABYLON.FilesInput = FilesInput;
  58738. })(BABYLON || (BABYLON = {}));
  58739. //# sourceMappingURL=babylon.filesInput.js.map
  58740. var BABYLON;
  58741. (function (BABYLON) {
  58742. /**
  58743. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58744. * The underlying implementation relies on an associative array to ensure the best performances.
  58745. * The value can be anything including 'null' but except 'undefined'
  58746. */
  58747. var StringDictionary = /** @class */ (function () {
  58748. function StringDictionary() {
  58749. this._count = 0;
  58750. this._data = {};
  58751. }
  58752. /**
  58753. * This will clear this dictionary and copy the content from the 'source' one.
  58754. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58755. * @param source the dictionary to take the content from and copy to this dictionary
  58756. */
  58757. StringDictionary.prototype.copyFrom = function (source) {
  58758. var _this = this;
  58759. this.clear();
  58760. source.forEach(function (t, v) { return _this.add(t, v); });
  58761. };
  58762. /**
  58763. * Get a value based from its key
  58764. * @param key the given key to get the matching value from
  58765. * @return the value if found, otherwise undefined is returned
  58766. */
  58767. StringDictionary.prototype.get = function (key) {
  58768. var val = this._data[key];
  58769. if (val !== undefined) {
  58770. return val;
  58771. }
  58772. return undefined;
  58773. };
  58774. /**
  58775. * Get a value from its key or add it if it doesn't exist.
  58776. * This method will ensure you that a given key/data will be present in the dictionary.
  58777. * @param key the given key to get the matching value from
  58778. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58779. * The factory will only be invoked if there's no data for the given key.
  58780. * @return the value corresponding to the key.
  58781. */
  58782. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58783. var val = this.get(key);
  58784. if (val !== undefined) {
  58785. return val;
  58786. }
  58787. val = factory(key);
  58788. if (val) {
  58789. this.add(key, val);
  58790. }
  58791. return val;
  58792. };
  58793. /**
  58794. * Get a value from its key if present in the dictionary otherwise add it
  58795. * @param key the key to get the value from
  58796. * @param val if there's no such key/value pair in the dictionary add it with this value
  58797. * @return the value corresponding to the key
  58798. */
  58799. StringDictionary.prototype.getOrAdd = function (key, val) {
  58800. var curVal = this.get(key);
  58801. if (curVal !== undefined) {
  58802. return curVal;
  58803. }
  58804. this.add(key, val);
  58805. return val;
  58806. };
  58807. /**
  58808. * Check if there's a given key in the dictionary
  58809. * @param key the key to check for
  58810. * @return true if the key is present, false otherwise
  58811. */
  58812. StringDictionary.prototype.contains = function (key) {
  58813. return this._data[key] !== undefined;
  58814. };
  58815. /**
  58816. * Add a new key and its corresponding value
  58817. * @param key the key to add
  58818. * @param value the value corresponding to the key
  58819. * @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
  58820. */
  58821. StringDictionary.prototype.add = function (key, value) {
  58822. if (this._data[key] !== undefined) {
  58823. return false;
  58824. }
  58825. this._data[key] = value;
  58826. ++this._count;
  58827. return true;
  58828. };
  58829. StringDictionary.prototype.set = function (key, value) {
  58830. if (this._data[key] === undefined) {
  58831. return false;
  58832. }
  58833. this._data[key] = value;
  58834. return true;
  58835. };
  58836. /**
  58837. * Get the element of the given key and remove it from the dictionary
  58838. * @param key
  58839. */
  58840. StringDictionary.prototype.getAndRemove = function (key) {
  58841. var val = this.get(key);
  58842. if (val !== undefined) {
  58843. delete this._data[key];
  58844. --this._count;
  58845. return val;
  58846. }
  58847. return null;
  58848. };
  58849. /**
  58850. * Remove a key/value from the dictionary.
  58851. * @param key the key to remove
  58852. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58853. */
  58854. StringDictionary.prototype.remove = function (key) {
  58855. if (this.contains(key)) {
  58856. delete this._data[key];
  58857. --this._count;
  58858. return true;
  58859. }
  58860. return false;
  58861. };
  58862. /**
  58863. * Clear the whole content of the dictionary
  58864. */
  58865. StringDictionary.prototype.clear = function () {
  58866. this._data = {};
  58867. this._count = 0;
  58868. };
  58869. Object.defineProperty(StringDictionary.prototype, "count", {
  58870. get: function () {
  58871. return this._count;
  58872. },
  58873. enumerable: true,
  58874. configurable: true
  58875. });
  58876. /**
  58877. * Execute a callback on each key/val of the dictionary.
  58878. * Note that you can remove any element in this dictionary in the callback implementation
  58879. * @param callback the callback to execute on a given key/value pair
  58880. */
  58881. StringDictionary.prototype.forEach = function (callback) {
  58882. for (var cur in this._data) {
  58883. var val = this._data[cur];
  58884. callback(cur, val);
  58885. }
  58886. };
  58887. /**
  58888. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58889. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58890. * Note that you can remove any element in this dictionary in the callback implementation
  58891. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58892. */
  58893. StringDictionary.prototype.first = function (callback) {
  58894. for (var cur in this._data) {
  58895. var val = this._data[cur];
  58896. var res = callback(cur, val);
  58897. if (res) {
  58898. return res;
  58899. }
  58900. }
  58901. return null;
  58902. };
  58903. return StringDictionary;
  58904. }());
  58905. BABYLON.StringDictionary = StringDictionary;
  58906. })(BABYLON || (BABYLON = {}));
  58907. //# sourceMappingURL=babylon.stringDictionary.js.map
  58908. var BABYLON;
  58909. (function (BABYLON) {
  58910. var Tags = /** @class */ (function () {
  58911. function Tags() {
  58912. }
  58913. Tags.EnableFor = function (obj) {
  58914. obj._tags = obj._tags || {};
  58915. obj.hasTags = function () {
  58916. return Tags.HasTags(obj);
  58917. };
  58918. obj.addTags = function (tagsString) {
  58919. return Tags.AddTagsTo(obj, tagsString);
  58920. };
  58921. obj.removeTags = function (tagsString) {
  58922. return Tags.RemoveTagsFrom(obj, tagsString);
  58923. };
  58924. obj.matchesTagsQuery = function (tagsQuery) {
  58925. return Tags.MatchesQuery(obj, tagsQuery);
  58926. };
  58927. };
  58928. Tags.DisableFor = function (obj) {
  58929. delete obj._tags;
  58930. delete obj.hasTags;
  58931. delete obj.addTags;
  58932. delete obj.removeTags;
  58933. delete obj.matchesTagsQuery;
  58934. };
  58935. Tags.HasTags = function (obj) {
  58936. if (!obj._tags) {
  58937. return false;
  58938. }
  58939. return !BABYLON.Tools.IsEmpty(obj._tags);
  58940. };
  58941. Tags.GetTags = function (obj, asString) {
  58942. if (asString === void 0) { asString = true; }
  58943. if (!obj._tags) {
  58944. return null;
  58945. }
  58946. if (asString) {
  58947. var tagsArray = [];
  58948. for (var tag in obj._tags) {
  58949. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  58950. tagsArray.push(tag);
  58951. }
  58952. }
  58953. return tagsArray.join(" ");
  58954. }
  58955. else {
  58956. return obj._tags;
  58957. }
  58958. };
  58959. // the tags 'true' and 'false' are reserved and cannot be used as tags
  58960. // a tag cannot start with '||', '&&', and '!'
  58961. // it cannot contain whitespaces
  58962. Tags.AddTagsTo = function (obj, tagsString) {
  58963. if (!tagsString) {
  58964. return;
  58965. }
  58966. if (typeof tagsString !== "string") {
  58967. return;
  58968. }
  58969. var tags = tagsString.split(" ");
  58970. tags.forEach(function (tag, index, array) {
  58971. Tags._AddTagTo(obj, tag);
  58972. });
  58973. };
  58974. Tags._AddTagTo = function (obj, tag) {
  58975. tag = tag.trim();
  58976. if (tag === "" || tag === "true" || tag === "false") {
  58977. return;
  58978. }
  58979. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  58980. return;
  58981. }
  58982. Tags.EnableFor(obj);
  58983. obj._tags[tag] = true;
  58984. };
  58985. Tags.RemoveTagsFrom = function (obj, tagsString) {
  58986. if (!Tags.HasTags(obj)) {
  58987. return;
  58988. }
  58989. var tags = tagsString.split(" ");
  58990. for (var t in tags) {
  58991. Tags._RemoveTagFrom(obj, tags[t]);
  58992. }
  58993. };
  58994. Tags._RemoveTagFrom = function (obj, tag) {
  58995. delete obj._tags[tag];
  58996. };
  58997. Tags.MatchesQuery = function (obj, tagsQuery) {
  58998. if (tagsQuery === undefined) {
  58999. return true;
  59000. }
  59001. if (tagsQuery === "") {
  59002. return Tags.HasTags(obj);
  59003. }
  59004. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  59005. };
  59006. return Tags;
  59007. }());
  59008. BABYLON.Tags = Tags;
  59009. })(BABYLON || (BABYLON = {}));
  59010. //# sourceMappingURL=babylon.tags.js.map
  59011. var BABYLON;
  59012. (function (BABYLON) {
  59013. var AndOrNotEvaluator = /** @class */ (function () {
  59014. function AndOrNotEvaluator() {
  59015. }
  59016. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  59017. if (!query.match(/\([^\(\)]*\)/g)) {
  59018. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  59019. }
  59020. else {
  59021. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  59022. // remove parenthesis
  59023. r = r.slice(1, r.length - 1);
  59024. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  59025. });
  59026. }
  59027. if (query === "true") {
  59028. return true;
  59029. }
  59030. if (query === "false") {
  59031. return false;
  59032. }
  59033. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  59034. };
  59035. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  59036. evaluateCallback = evaluateCallback || (function (r) {
  59037. return r === "true" ? true : false;
  59038. });
  59039. var result;
  59040. var or = parenthesisContent.split("||");
  59041. for (var i in or) {
  59042. if (or.hasOwnProperty(i)) {
  59043. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  59044. var and = ori.split("&&");
  59045. if (and.length > 1) {
  59046. for (var j = 0; j < and.length; ++j) {
  59047. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  59048. if (andj !== "true" && andj !== "false") {
  59049. if (andj[0] === "!") {
  59050. result = !evaluateCallback(andj.substring(1));
  59051. }
  59052. else {
  59053. result = evaluateCallback(andj);
  59054. }
  59055. }
  59056. else {
  59057. result = andj === "true" ? true : false;
  59058. }
  59059. if (!result) {
  59060. ori = "false";
  59061. break;
  59062. }
  59063. }
  59064. }
  59065. if (result || ori === "true") {
  59066. result = true;
  59067. break;
  59068. }
  59069. // result equals false (or undefined)
  59070. if (ori !== "true" && ori !== "false") {
  59071. if (ori[0] === "!") {
  59072. result = !evaluateCallback(ori.substring(1));
  59073. }
  59074. else {
  59075. result = evaluateCallback(ori);
  59076. }
  59077. }
  59078. else {
  59079. result = ori === "true" ? true : false;
  59080. }
  59081. }
  59082. }
  59083. // the whole parenthesis scope is replaced by 'true' or 'false'
  59084. return result ? "true" : "false";
  59085. };
  59086. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  59087. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  59088. // remove whitespaces
  59089. r = r.replace(/[\s]/g, function () { return ""; });
  59090. return r.length % 2 ? "!" : "";
  59091. });
  59092. booleanString = booleanString.trim();
  59093. if (booleanString === "!true") {
  59094. booleanString = "false";
  59095. }
  59096. else if (booleanString === "!false") {
  59097. booleanString = "true";
  59098. }
  59099. return booleanString;
  59100. };
  59101. return AndOrNotEvaluator;
  59102. }());
  59103. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  59104. })(BABYLON || (BABYLON = {}));
  59105. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  59106. var BABYLON;
  59107. (function (BABYLON) {
  59108. var Database = /** @class */ (function () {
  59109. function Database(urlToScene, callbackManifestChecked) {
  59110. // Handling various flavors of prefixed version of IndexedDB
  59111. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  59112. this.callbackManifestChecked = callbackManifestChecked;
  59113. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  59114. this.db = null;
  59115. this._enableSceneOffline = false;
  59116. this._enableTexturesOffline = false;
  59117. this.manifestVersionFound = 0;
  59118. this.mustUpdateRessources = false;
  59119. this.hasReachedQuota = false;
  59120. if (!Database.IDBStorageEnabled) {
  59121. this.callbackManifestChecked(true);
  59122. }
  59123. else {
  59124. this.checkManifestFile();
  59125. }
  59126. }
  59127. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  59128. get: function () {
  59129. return this._enableSceneOffline;
  59130. },
  59131. enumerable: true,
  59132. configurable: true
  59133. });
  59134. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  59135. get: function () {
  59136. return this._enableTexturesOffline;
  59137. },
  59138. enumerable: true,
  59139. configurable: true
  59140. });
  59141. Database.prototype.checkManifestFile = function () {
  59142. var _this = this;
  59143. var noManifestFile = function () {
  59144. _this._enableSceneOffline = false;
  59145. _this._enableTexturesOffline = false;
  59146. _this.callbackManifestChecked(false);
  59147. };
  59148. var timeStampUsed = false;
  59149. var manifestURL = this.currentSceneUrl + ".manifest";
  59150. var xhr = new XMLHttpRequest();
  59151. if (navigator.onLine) {
  59152. // Adding a timestamp to by-pass browsers' cache
  59153. timeStampUsed = true;
  59154. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  59155. }
  59156. xhr.open("GET", manifestURL, true);
  59157. xhr.addEventListener("load", function () {
  59158. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59159. try {
  59160. var manifestFile = JSON.parse(xhr.response);
  59161. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  59162. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  59163. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  59164. _this.manifestVersionFound = manifestFile.version;
  59165. }
  59166. if (_this.callbackManifestChecked) {
  59167. _this.callbackManifestChecked(true);
  59168. }
  59169. }
  59170. catch (ex) {
  59171. noManifestFile();
  59172. }
  59173. }
  59174. else {
  59175. noManifestFile();
  59176. }
  59177. }, false);
  59178. xhr.addEventListener("error", function (event) {
  59179. if (timeStampUsed) {
  59180. timeStampUsed = false;
  59181. // Let's retry without the timeStamp
  59182. // It could fail when coupled with HTML5 Offline API
  59183. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  59184. xhr.open("GET", retryManifestURL, true);
  59185. xhr.send();
  59186. }
  59187. else {
  59188. noManifestFile();
  59189. }
  59190. }, false);
  59191. try {
  59192. xhr.send();
  59193. }
  59194. catch (ex) {
  59195. BABYLON.Tools.Error("Error on XHR send request.");
  59196. this.callbackManifestChecked(false);
  59197. }
  59198. };
  59199. Database.prototype.openAsync = function (successCallback, errorCallback) {
  59200. var _this = this;
  59201. var handleError = function () {
  59202. _this.isSupported = false;
  59203. if (errorCallback)
  59204. errorCallback();
  59205. };
  59206. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  59207. // Your browser doesn't support IndexedDB
  59208. this.isSupported = false;
  59209. if (errorCallback)
  59210. errorCallback();
  59211. }
  59212. else {
  59213. // If the DB hasn't been opened or created yet
  59214. if (!this.db) {
  59215. this.hasReachedQuota = false;
  59216. this.isSupported = true;
  59217. var request = this.idbFactory.open("babylonjs", 1);
  59218. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  59219. request.onerror = function (event) {
  59220. handleError();
  59221. };
  59222. // executes when a version change transaction cannot complete due to other active transactions
  59223. request.onblocked = function (event) {
  59224. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  59225. handleError();
  59226. };
  59227. // DB has been opened successfully
  59228. request.onsuccess = function (event) {
  59229. _this.db = request.result;
  59230. successCallback();
  59231. };
  59232. // Initialization of the DB. Creating Scenes & Textures stores
  59233. request.onupgradeneeded = function (event) {
  59234. _this.db = (event.target).result;
  59235. if (_this.db) {
  59236. try {
  59237. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  59238. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  59239. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  59240. }
  59241. catch (ex) {
  59242. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  59243. handleError();
  59244. }
  59245. }
  59246. };
  59247. }
  59248. else {
  59249. if (successCallback)
  59250. successCallback();
  59251. }
  59252. }
  59253. };
  59254. Database.prototype.loadImageFromDB = function (url, image) {
  59255. var _this = this;
  59256. var completeURL = Database.ReturnFullUrlLocation(url);
  59257. var saveAndLoadImage = function () {
  59258. if (!_this.hasReachedQuota && _this.db !== null) {
  59259. // the texture is not yet in the DB, let's try to save it
  59260. _this._saveImageIntoDBAsync(completeURL, image);
  59261. }
  59262. else {
  59263. image.src = url;
  59264. }
  59265. };
  59266. if (!this.mustUpdateRessources) {
  59267. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  59268. }
  59269. else {
  59270. saveAndLoadImage();
  59271. }
  59272. };
  59273. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  59274. if (this.isSupported && this.db !== null) {
  59275. var texture;
  59276. var transaction = this.db.transaction(["textures"]);
  59277. transaction.onabort = function (event) {
  59278. image.src = url;
  59279. };
  59280. transaction.oncomplete = function (event) {
  59281. var blobTextureURL;
  59282. if (texture) {
  59283. var URL = window.URL || window.webkitURL;
  59284. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  59285. image.onerror = function () {
  59286. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  59287. image.src = url;
  59288. };
  59289. image.src = blobTextureURL;
  59290. }
  59291. else {
  59292. notInDBCallback();
  59293. }
  59294. };
  59295. var getRequest = transaction.objectStore("textures").get(url);
  59296. getRequest.onsuccess = function (event) {
  59297. texture = (event.target).result;
  59298. };
  59299. getRequest.onerror = function (event) {
  59300. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  59301. image.src = url;
  59302. };
  59303. }
  59304. else {
  59305. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59306. image.src = url;
  59307. }
  59308. };
  59309. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  59310. var _this = this;
  59311. if (this.isSupported) {
  59312. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  59313. var generateBlobUrl = function () {
  59314. var blobTextureURL;
  59315. if (blob) {
  59316. var URL = window.URL || window.webkitURL;
  59317. try {
  59318. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  59319. }
  59320. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  59321. catch (ex) {
  59322. blobTextureURL = URL.createObjectURL(blob);
  59323. }
  59324. }
  59325. if (blobTextureURL) {
  59326. image.src = blobTextureURL;
  59327. }
  59328. };
  59329. if (Database.IsUASupportingBlobStorage) {
  59330. var xhr = new XMLHttpRequest(), blob;
  59331. xhr.open("GET", url, true);
  59332. xhr.responseType = "blob";
  59333. xhr.addEventListener("load", function () {
  59334. if (xhr.status === 200 && _this.db) {
  59335. // Blob as response (XHR2)
  59336. blob = xhr.response;
  59337. var transaction = _this.db.transaction(["textures"], "readwrite");
  59338. // the transaction could abort because of a QuotaExceededError error
  59339. transaction.onabort = function (event) {
  59340. try {
  59341. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59342. var srcElement = (event.srcElement || event.target);
  59343. var error = srcElement.error;
  59344. if (error && error.name === "QuotaExceededError") {
  59345. _this.hasReachedQuota = true;
  59346. }
  59347. }
  59348. catch (ex) { }
  59349. generateBlobUrl();
  59350. };
  59351. transaction.oncomplete = function (event) {
  59352. generateBlobUrl();
  59353. };
  59354. var newTexture = { textureUrl: url, data: blob };
  59355. try {
  59356. // Put the blob into the dabase
  59357. var addRequest = transaction.objectStore("textures").put(newTexture);
  59358. addRequest.onsuccess = function (event) {
  59359. };
  59360. addRequest.onerror = function (event) {
  59361. generateBlobUrl();
  59362. };
  59363. }
  59364. catch (ex) {
  59365. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  59366. if (ex.code === 25) {
  59367. Database.IsUASupportingBlobStorage = false;
  59368. }
  59369. image.src = url;
  59370. }
  59371. }
  59372. else {
  59373. image.src = url;
  59374. }
  59375. }, false);
  59376. xhr.addEventListener("error", function (event) {
  59377. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  59378. image.src = url;
  59379. }, false);
  59380. xhr.send();
  59381. }
  59382. else {
  59383. image.src = url;
  59384. }
  59385. }
  59386. else {
  59387. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59388. image.src = url;
  59389. }
  59390. };
  59391. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  59392. var _this = this;
  59393. var updateVersion = function () {
  59394. // the version is not yet in the DB or we need to update it
  59395. _this._saveVersionIntoDBAsync(url, versionLoaded);
  59396. };
  59397. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  59398. };
  59399. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  59400. var _this = this;
  59401. if (this.isSupported && this.db) {
  59402. var version;
  59403. try {
  59404. var transaction = this.db.transaction(["versions"]);
  59405. transaction.oncomplete = function (event) {
  59406. if (version) {
  59407. // If the version in the JSON file is > than the version in DB
  59408. if (_this.manifestVersionFound > version.data) {
  59409. _this.mustUpdateRessources = true;
  59410. updateInDBCallback();
  59411. }
  59412. else {
  59413. callback(version.data);
  59414. }
  59415. }
  59416. else {
  59417. _this.mustUpdateRessources = true;
  59418. updateInDBCallback();
  59419. }
  59420. };
  59421. transaction.onabort = function (event) {
  59422. callback(-1);
  59423. };
  59424. var getRequest = transaction.objectStore("versions").get(url);
  59425. getRequest.onsuccess = function (event) {
  59426. version = (event.target).result;
  59427. };
  59428. getRequest.onerror = function (event) {
  59429. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  59430. callback(-1);
  59431. };
  59432. }
  59433. catch (ex) {
  59434. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  59435. callback(-1);
  59436. }
  59437. }
  59438. else {
  59439. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59440. callback(-1);
  59441. }
  59442. };
  59443. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  59444. var _this = this;
  59445. if (this.isSupported && !this.hasReachedQuota && this.db) {
  59446. try {
  59447. // Open a transaction to the database
  59448. var transaction = this.db.transaction(["versions"], "readwrite");
  59449. // the transaction could abort because of a QuotaExceededError error
  59450. transaction.onabort = function (event) {
  59451. try {
  59452. var error = event.srcElement['error'];
  59453. if (error && error.name === "QuotaExceededError") {
  59454. _this.hasReachedQuota = true;
  59455. }
  59456. }
  59457. catch (ex) { }
  59458. callback(-1);
  59459. };
  59460. transaction.oncomplete = function (event) {
  59461. callback(_this.manifestVersionFound);
  59462. };
  59463. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  59464. // Put the scene into the database
  59465. var addRequest = transaction.objectStore("versions").put(newVersion);
  59466. addRequest.onsuccess = function (event) {
  59467. };
  59468. addRequest.onerror = function (event) {
  59469. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  59470. };
  59471. }
  59472. catch (ex) {
  59473. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  59474. callback(-1);
  59475. }
  59476. }
  59477. else {
  59478. callback(-1);
  59479. }
  59480. };
  59481. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  59482. var _this = this;
  59483. var completeUrl = Database.ReturnFullUrlLocation(url);
  59484. var saveAndLoadFile = function () {
  59485. // the scene is not yet in the DB, let's try to save it
  59486. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  59487. };
  59488. this._checkVersionFromDB(completeUrl, function (version) {
  59489. if (version !== -1) {
  59490. if (!_this.mustUpdateRessources) {
  59491. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  59492. }
  59493. else {
  59494. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  59495. }
  59496. }
  59497. else {
  59498. if (errorCallback) {
  59499. errorCallback();
  59500. }
  59501. }
  59502. });
  59503. };
  59504. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  59505. if (this.isSupported && this.db) {
  59506. var targetStore;
  59507. if (url.indexOf(".babylon") !== -1) {
  59508. targetStore = "scenes";
  59509. }
  59510. else {
  59511. targetStore = "textures";
  59512. }
  59513. var file;
  59514. var transaction = this.db.transaction([targetStore]);
  59515. transaction.oncomplete = function (event) {
  59516. if (file) {
  59517. callback(file.data);
  59518. }
  59519. else {
  59520. notInDBCallback();
  59521. }
  59522. };
  59523. transaction.onabort = function (event) {
  59524. notInDBCallback();
  59525. };
  59526. var getRequest = transaction.objectStore(targetStore).get(url);
  59527. getRequest.onsuccess = function (event) {
  59528. file = (event.target).result;
  59529. };
  59530. getRequest.onerror = function (event) {
  59531. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  59532. notInDBCallback();
  59533. };
  59534. }
  59535. else {
  59536. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59537. callback();
  59538. }
  59539. };
  59540. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  59541. var _this = this;
  59542. if (this.isSupported) {
  59543. var targetStore;
  59544. if (url.indexOf(".babylon") !== -1) {
  59545. targetStore = "scenes";
  59546. }
  59547. else {
  59548. targetStore = "textures";
  59549. }
  59550. // Create XHR
  59551. var xhr = new XMLHttpRequest();
  59552. var fileData;
  59553. xhr.open("GET", url, true);
  59554. if (useArrayBuffer) {
  59555. xhr.responseType = "arraybuffer";
  59556. }
  59557. if (progressCallback) {
  59558. xhr.onprogress = progressCallback;
  59559. }
  59560. xhr.addEventListener("load", function () {
  59561. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  59562. // Blob as response (XHR2)
  59563. //fileData = xhr.responseText;
  59564. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  59565. if (!_this.hasReachedQuota && _this.db) {
  59566. // Open a transaction to the database
  59567. var transaction = _this.db.transaction([targetStore], "readwrite");
  59568. // the transaction could abort because of a QuotaExceededError error
  59569. transaction.onabort = function (event) {
  59570. try {
  59571. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59572. var error = event.srcElement['error'];
  59573. if (error && error.name === "QuotaExceededError") {
  59574. _this.hasReachedQuota = true;
  59575. }
  59576. }
  59577. catch (ex) { }
  59578. callback(fileData);
  59579. };
  59580. transaction.oncomplete = function (event) {
  59581. callback(fileData);
  59582. };
  59583. var newFile;
  59584. if (targetStore === "scenes") {
  59585. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  59586. }
  59587. else {
  59588. newFile = { textureUrl: url, data: fileData };
  59589. }
  59590. try {
  59591. // Put the scene into the database
  59592. var addRequest = transaction.objectStore(targetStore).put(newFile);
  59593. addRequest.onsuccess = function (event) {
  59594. };
  59595. addRequest.onerror = function (event) {
  59596. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  59597. };
  59598. }
  59599. catch (ex) {
  59600. callback(fileData);
  59601. }
  59602. }
  59603. else {
  59604. callback(fileData);
  59605. }
  59606. }
  59607. else {
  59608. callback();
  59609. }
  59610. }, false);
  59611. xhr.addEventListener("error", function (event) {
  59612. BABYLON.Tools.Error("error on XHR request.");
  59613. callback();
  59614. }, false);
  59615. xhr.send();
  59616. }
  59617. else {
  59618. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59619. callback();
  59620. }
  59621. };
  59622. Database.IsUASupportingBlobStorage = true;
  59623. Database.IDBStorageEnabled = true;
  59624. Database.parseURL = function (url) {
  59625. var a = document.createElement('a');
  59626. a.href = url;
  59627. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  59628. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  59629. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  59630. return absLocation;
  59631. };
  59632. Database.ReturnFullUrlLocation = function (url) {
  59633. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  59634. return (Database.parseURL(window.location.href) + url);
  59635. }
  59636. else {
  59637. return url;
  59638. }
  59639. };
  59640. return Database;
  59641. }());
  59642. BABYLON.Database = Database;
  59643. })(BABYLON || (BABYLON = {}));
  59644. //# sourceMappingURL=babylon.database.js.map
  59645. var BABYLON;
  59646. (function (BABYLON) {
  59647. var FresnelParameters = /** @class */ (function () {
  59648. function FresnelParameters() {
  59649. this._isEnabled = true;
  59650. this.leftColor = BABYLON.Color3.White();
  59651. this.rightColor = BABYLON.Color3.Black();
  59652. this.bias = 0;
  59653. this.power = 1;
  59654. }
  59655. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  59656. get: function () {
  59657. return this._isEnabled;
  59658. },
  59659. set: function (value) {
  59660. if (this._isEnabled === value) {
  59661. return;
  59662. }
  59663. this._isEnabled = value;
  59664. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  59665. },
  59666. enumerable: true,
  59667. configurable: true
  59668. });
  59669. FresnelParameters.prototype.clone = function () {
  59670. var newFresnelParameters = new FresnelParameters();
  59671. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  59672. return newFresnelParameters;
  59673. };
  59674. FresnelParameters.prototype.serialize = function () {
  59675. var serializationObject = {};
  59676. serializationObject.isEnabled = this.isEnabled;
  59677. serializationObject.leftColor = this.leftColor;
  59678. serializationObject.rightColor = this.rightColor;
  59679. serializationObject.bias = this.bias;
  59680. serializationObject.power = this.power;
  59681. return serializationObject;
  59682. };
  59683. FresnelParameters.Parse = function (parsedFresnelParameters) {
  59684. var fresnelParameters = new FresnelParameters();
  59685. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  59686. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  59687. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  59688. fresnelParameters.bias = parsedFresnelParameters.bias;
  59689. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  59690. return fresnelParameters;
  59691. };
  59692. return FresnelParameters;
  59693. }());
  59694. BABYLON.FresnelParameters = FresnelParameters;
  59695. })(BABYLON || (BABYLON = {}));
  59696. //# sourceMappingURL=babylon.fresnelParameters.js.map
  59697. var BABYLON;
  59698. (function (BABYLON) {
  59699. var MultiMaterial = /** @class */ (function (_super) {
  59700. __extends(MultiMaterial, _super);
  59701. function MultiMaterial(name, scene) {
  59702. var _this = _super.call(this, name, scene, true) || this;
  59703. scene.multiMaterials.push(_this);
  59704. _this.subMaterials = new Array();
  59705. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  59706. return _this;
  59707. }
  59708. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  59709. get: function () {
  59710. return this._subMaterials;
  59711. },
  59712. set: function (value) {
  59713. this._subMaterials = value;
  59714. this._hookArray(value);
  59715. },
  59716. enumerable: true,
  59717. configurable: true
  59718. });
  59719. MultiMaterial.prototype._hookArray = function (array) {
  59720. var _this = this;
  59721. var oldPush = array.push;
  59722. array.push = function () {
  59723. var items = [];
  59724. for (var _i = 0; _i < arguments.length; _i++) {
  59725. items[_i] = arguments[_i];
  59726. }
  59727. var result = oldPush.apply(array, items);
  59728. _this._markAllSubMeshesAsTexturesDirty();
  59729. return result;
  59730. };
  59731. var oldSplice = array.splice;
  59732. array.splice = function (index, deleteCount) {
  59733. var deleted = oldSplice.apply(array, [index, deleteCount]);
  59734. _this._markAllSubMeshesAsTexturesDirty();
  59735. return deleted;
  59736. };
  59737. };
  59738. // Properties
  59739. MultiMaterial.prototype.getSubMaterial = function (index) {
  59740. if (index < 0 || index >= this.subMaterials.length) {
  59741. return this.getScene().defaultMaterial;
  59742. }
  59743. return this.subMaterials[index];
  59744. };
  59745. MultiMaterial.prototype.getActiveTextures = function () {
  59746. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  59747. if (subMaterial) {
  59748. return subMaterial.getActiveTextures();
  59749. }
  59750. else {
  59751. return [];
  59752. }
  59753. }));
  59754. var _a;
  59755. };
  59756. // Methods
  59757. MultiMaterial.prototype.getClassName = function () {
  59758. return "MultiMaterial";
  59759. };
  59760. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  59761. for (var index = 0; index < this.subMaterials.length; index++) {
  59762. var subMaterial = this.subMaterials[index];
  59763. if (subMaterial) {
  59764. if (subMaterial.storeEffectOnSubMeshes) {
  59765. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  59766. return false;
  59767. }
  59768. continue;
  59769. }
  59770. if (!subMaterial.isReady(mesh)) {
  59771. return false;
  59772. }
  59773. }
  59774. }
  59775. return true;
  59776. };
  59777. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  59778. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  59779. for (var index = 0; index < this.subMaterials.length; index++) {
  59780. var subMaterial = null;
  59781. var current = this.subMaterials[index];
  59782. if (cloneChildren && current) {
  59783. subMaterial = current.clone(name + "-" + current.name);
  59784. }
  59785. else {
  59786. subMaterial = this.subMaterials[index];
  59787. }
  59788. newMultiMaterial.subMaterials.push(subMaterial);
  59789. }
  59790. return newMultiMaterial;
  59791. };
  59792. MultiMaterial.prototype.serialize = function () {
  59793. var serializationObject = {};
  59794. serializationObject.name = this.name;
  59795. serializationObject.id = this.id;
  59796. if (BABYLON.Tags) {
  59797. serializationObject.tags = BABYLON.Tags.GetTags(this);
  59798. }
  59799. serializationObject.materials = [];
  59800. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  59801. var subMat = this.subMaterials[matIndex];
  59802. if (subMat) {
  59803. serializationObject.materials.push(subMat.id);
  59804. }
  59805. else {
  59806. serializationObject.materials.push(null);
  59807. }
  59808. }
  59809. return serializationObject;
  59810. };
  59811. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59812. var scene = this.getScene();
  59813. if (!scene) {
  59814. return;
  59815. }
  59816. var index = scene.multiMaterials.indexOf(this);
  59817. if (index >= 0) {
  59818. scene.multiMaterials.splice(index, 1);
  59819. }
  59820. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59821. };
  59822. return MultiMaterial;
  59823. }(BABYLON.Material));
  59824. BABYLON.MultiMaterial = MultiMaterial;
  59825. })(BABYLON || (BABYLON = {}));
  59826. //# sourceMappingURL=babylon.multiMaterial.js.map
  59827. var BABYLON;
  59828. (function (BABYLON) {
  59829. var FreeCameraTouchInput = /** @class */ (function () {
  59830. function FreeCameraTouchInput() {
  59831. this._offsetX = null;
  59832. this._offsetY = null;
  59833. this._pointerPressed = new Array();
  59834. this.touchAngularSensibility = 200000.0;
  59835. this.touchMoveSensibility = 250.0;
  59836. }
  59837. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  59838. var _this = this;
  59839. var previousPosition = null;
  59840. if (this._pointerInput === undefined) {
  59841. this._onLostFocus = function (evt) {
  59842. _this._offsetX = null;
  59843. _this._offsetY = null;
  59844. };
  59845. this._pointerInput = function (p, s) {
  59846. var evt = p.event;
  59847. if (evt.pointerType === "mouse") {
  59848. return;
  59849. }
  59850. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  59851. if (!noPreventDefault) {
  59852. evt.preventDefault();
  59853. }
  59854. _this._pointerPressed.push(evt.pointerId);
  59855. if (_this._pointerPressed.length !== 1) {
  59856. return;
  59857. }
  59858. previousPosition = {
  59859. x: evt.clientX,
  59860. y: evt.clientY
  59861. };
  59862. }
  59863. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  59864. if (!noPreventDefault) {
  59865. evt.preventDefault();
  59866. }
  59867. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59868. if (index === -1) {
  59869. return;
  59870. }
  59871. _this._pointerPressed.splice(index, 1);
  59872. if (index != 0) {
  59873. return;
  59874. }
  59875. previousPosition = null;
  59876. _this._offsetX = null;
  59877. _this._offsetY = null;
  59878. }
  59879. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  59880. if (!noPreventDefault) {
  59881. evt.preventDefault();
  59882. }
  59883. if (!previousPosition) {
  59884. return;
  59885. }
  59886. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59887. if (index != 0) {
  59888. return;
  59889. }
  59890. _this._offsetX = evt.clientX - previousPosition.x;
  59891. _this._offsetY = -(evt.clientY - previousPosition.y);
  59892. }
  59893. };
  59894. }
  59895. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  59896. if (this._onLostFocus) {
  59897. element.addEventListener("blur", this._onLostFocus);
  59898. }
  59899. };
  59900. FreeCameraTouchInput.prototype.detachControl = function (element) {
  59901. if (this._pointerInput && element) {
  59902. if (this._observer) {
  59903. this.camera.getScene().onPointerObservable.remove(this._observer);
  59904. this._observer = null;
  59905. }
  59906. if (this._onLostFocus) {
  59907. element.removeEventListener("blur", this._onLostFocus);
  59908. this._onLostFocus = null;
  59909. }
  59910. this._pointerPressed = [];
  59911. this._offsetX = null;
  59912. this._offsetY = null;
  59913. }
  59914. };
  59915. FreeCameraTouchInput.prototype.checkInputs = function () {
  59916. if (this._offsetX && this._offsetY) {
  59917. var camera = this.camera;
  59918. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  59919. if (this._pointerPressed.length > 1) {
  59920. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  59921. }
  59922. else {
  59923. var speed = camera._computeLocalCameraSpeed();
  59924. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  59925. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  59926. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  59927. }
  59928. }
  59929. };
  59930. FreeCameraTouchInput.prototype.getClassName = function () {
  59931. return "FreeCameraTouchInput";
  59932. };
  59933. FreeCameraTouchInput.prototype.getSimpleName = function () {
  59934. return "touch";
  59935. };
  59936. __decorate([
  59937. BABYLON.serialize()
  59938. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  59939. __decorate([
  59940. BABYLON.serialize()
  59941. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  59942. return FreeCameraTouchInput;
  59943. }());
  59944. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  59945. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  59946. })(BABYLON || (BABYLON = {}));
  59947. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  59948. var BABYLON;
  59949. (function (BABYLON) {
  59950. // We're mainly based on the logic defined into the FreeCamera code
  59951. var TouchCamera = /** @class */ (function (_super) {
  59952. __extends(TouchCamera, _super);
  59953. //-- end properties for backward compatibility for inputs
  59954. function TouchCamera(name, position, scene) {
  59955. var _this = _super.call(this, name, position, scene) || this;
  59956. _this.inputs.addTouch();
  59957. _this._setupInputs();
  59958. return _this;
  59959. }
  59960. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  59961. //-- Begin properties for backward compatibility for inputs
  59962. get: function () {
  59963. var touch = this.inputs.attached["touch"];
  59964. if (touch)
  59965. return touch.touchAngularSensibility;
  59966. return 0;
  59967. },
  59968. set: function (value) {
  59969. var touch = this.inputs.attached["touch"];
  59970. if (touch)
  59971. touch.touchAngularSensibility = value;
  59972. },
  59973. enumerable: true,
  59974. configurable: true
  59975. });
  59976. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  59977. get: function () {
  59978. var touch = this.inputs.attached["touch"];
  59979. if (touch)
  59980. return touch.touchMoveSensibility;
  59981. return 0;
  59982. },
  59983. set: function (value) {
  59984. var touch = this.inputs.attached["touch"];
  59985. if (touch)
  59986. touch.touchMoveSensibility = value;
  59987. },
  59988. enumerable: true,
  59989. configurable: true
  59990. });
  59991. TouchCamera.prototype.getClassName = function () {
  59992. return "TouchCamera";
  59993. };
  59994. TouchCamera.prototype._setupInputs = function () {
  59995. var mouse = this.inputs.attached["mouse"];
  59996. if (mouse) {
  59997. mouse.touchEnabled = false;
  59998. }
  59999. };
  60000. return TouchCamera;
  60001. }(BABYLON.FreeCamera));
  60002. BABYLON.TouchCamera = TouchCamera;
  60003. })(BABYLON || (BABYLON = {}));
  60004. //# sourceMappingURL=babylon.touchCamera.js.map
  60005. var BABYLON;
  60006. (function (BABYLON) {
  60007. var ProceduralTexture = /** @class */ (function (_super) {
  60008. __extends(ProceduralTexture, _super);
  60009. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  60010. if (fallbackTexture === void 0) { fallbackTexture = null; }
  60011. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60012. if (isCube === void 0) { isCube = false; }
  60013. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  60014. _this.isCube = isCube;
  60015. _this.isEnabled = true;
  60016. _this._currentRefreshId = -1;
  60017. _this._refreshRate = 1;
  60018. _this._vertexBuffers = {};
  60019. _this._uniforms = new Array();
  60020. _this._samplers = new Array();
  60021. _this._textures = {};
  60022. _this._floats = {};
  60023. _this._floatsArrays = {};
  60024. _this._colors3 = {};
  60025. _this._colors4 = {};
  60026. _this._vectors2 = {};
  60027. _this._vectors3 = {};
  60028. _this._matrices = {};
  60029. _this._fallbackTextureUsed = false;
  60030. scene._proceduralTextures.push(_this);
  60031. _this._engine = scene.getEngine();
  60032. _this.name = name;
  60033. _this.isRenderTarget = true;
  60034. _this._size = size;
  60035. _this._generateMipMaps = generateMipMaps;
  60036. _this.setFragment(fragment);
  60037. _this._fallbackTexture = fallbackTexture;
  60038. if (isCube) {
  60039. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  60040. _this.setFloat("face", 0);
  60041. }
  60042. else {
  60043. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  60044. }
  60045. // VBO
  60046. var vertices = [];
  60047. vertices.push(1, 1);
  60048. vertices.push(-1, 1);
  60049. vertices.push(-1, -1);
  60050. vertices.push(1, -1);
  60051. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60052. _this._createIndexBuffer();
  60053. return _this;
  60054. }
  60055. ProceduralTexture.prototype._createIndexBuffer = function () {
  60056. var engine = this._engine;
  60057. // Indices
  60058. var indices = [];
  60059. indices.push(0);
  60060. indices.push(1);
  60061. indices.push(2);
  60062. indices.push(0);
  60063. indices.push(2);
  60064. indices.push(3);
  60065. this._indexBuffer = engine.createIndexBuffer(indices);
  60066. };
  60067. ProceduralTexture.prototype._rebuild = function () {
  60068. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60069. if (vb) {
  60070. vb._rebuild();
  60071. }
  60072. this._createIndexBuffer();
  60073. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  60074. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  60075. }
  60076. };
  60077. ProceduralTexture.prototype.reset = function () {
  60078. if (this._effect === undefined) {
  60079. return;
  60080. }
  60081. var engine = this._engine;
  60082. engine._releaseEffect(this._effect);
  60083. };
  60084. ProceduralTexture.prototype.isReady = function () {
  60085. var _this = this;
  60086. var engine = this._engine;
  60087. var shaders;
  60088. if (!this._fragment) {
  60089. return false;
  60090. }
  60091. if (this._fallbackTextureUsed) {
  60092. return true;
  60093. }
  60094. if (this._fragment.fragmentElement !== undefined) {
  60095. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  60096. }
  60097. else {
  60098. shaders = { vertex: "procedural", fragment: this._fragment };
  60099. }
  60100. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  60101. _this.releaseInternalTexture();
  60102. if (_this._fallbackTexture) {
  60103. _this._texture = _this._fallbackTexture._texture;
  60104. if (_this._texture) {
  60105. _this._texture.incrementReferences();
  60106. }
  60107. }
  60108. _this._fallbackTextureUsed = true;
  60109. });
  60110. return this._effect.isReady();
  60111. };
  60112. ProceduralTexture.prototype.resetRefreshCounter = function () {
  60113. this._currentRefreshId = -1;
  60114. };
  60115. ProceduralTexture.prototype.setFragment = function (fragment) {
  60116. this._fragment = fragment;
  60117. };
  60118. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  60119. get: function () {
  60120. return this._refreshRate;
  60121. },
  60122. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  60123. set: function (value) {
  60124. this._refreshRate = value;
  60125. this.resetRefreshCounter();
  60126. },
  60127. enumerable: true,
  60128. configurable: true
  60129. });
  60130. ProceduralTexture.prototype._shouldRender = function () {
  60131. if (!this.isEnabled || !this.isReady() || !this._texture) {
  60132. return false;
  60133. }
  60134. if (this._fallbackTextureUsed) {
  60135. return false;
  60136. }
  60137. if (this._currentRefreshId === -1) {
  60138. this._currentRefreshId = 1;
  60139. return true;
  60140. }
  60141. if (this.refreshRate === this._currentRefreshId) {
  60142. this._currentRefreshId = 1;
  60143. return true;
  60144. }
  60145. this._currentRefreshId++;
  60146. return false;
  60147. };
  60148. ProceduralTexture.prototype.getRenderSize = function () {
  60149. return this._size;
  60150. };
  60151. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  60152. if (this._fallbackTextureUsed) {
  60153. return;
  60154. }
  60155. this.releaseInternalTexture();
  60156. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  60157. };
  60158. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  60159. if (this._uniforms.indexOf(uniformName) === -1) {
  60160. this._uniforms.push(uniformName);
  60161. }
  60162. };
  60163. ProceduralTexture.prototype.setTexture = function (name, texture) {
  60164. if (this._samplers.indexOf(name) === -1) {
  60165. this._samplers.push(name);
  60166. }
  60167. this._textures[name] = texture;
  60168. return this;
  60169. };
  60170. ProceduralTexture.prototype.setFloat = function (name, value) {
  60171. this._checkUniform(name);
  60172. this._floats[name] = value;
  60173. return this;
  60174. };
  60175. ProceduralTexture.prototype.setFloats = function (name, value) {
  60176. this._checkUniform(name);
  60177. this._floatsArrays[name] = value;
  60178. return this;
  60179. };
  60180. ProceduralTexture.prototype.setColor3 = function (name, value) {
  60181. this._checkUniform(name);
  60182. this._colors3[name] = value;
  60183. return this;
  60184. };
  60185. ProceduralTexture.prototype.setColor4 = function (name, value) {
  60186. this._checkUniform(name);
  60187. this._colors4[name] = value;
  60188. return this;
  60189. };
  60190. ProceduralTexture.prototype.setVector2 = function (name, value) {
  60191. this._checkUniform(name);
  60192. this._vectors2[name] = value;
  60193. return this;
  60194. };
  60195. ProceduralTexture.prototype.setVector3 = function (name, value) {
  60196. this._checkUniform(name);
  60197. this._vectors3[name] = value;
  60198. return this;
  60199. };
  60200. ProceduralTexture.prototype.setMatrix = function (name, value) {
  60201. this._checkUniform(name);
  60202. this._matrices[name] = value;
  60203. return this;
  60204. };
  60205. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60206. var scene = this.getScene();
  60207. if (!scene) {
  60208. return;
  60209. }
  60210. var engine = this._engine;
  60211. // Render
  60212. engine.enableEffect(this._effect);
  60213. engine.setState(false);
  60214. // Texture
  60215. for (var name in this._textures) {
  60216. this._effect.setTexture(name, this._textures[name]);
  60217. }
  60218. // Float
  60219. for (name in this._floats) {
  60220. this._effect.setFloat(name, this._floats[name]);
  60221. }
  60222. // Floats
  60223. for (name in this._floatsArrays) {
  60224. this._effect.setArray(name, this._floatsArrays[name]);
  60225. }
  60226. // Color3
  60227. for (name in this._colors3) {
  60228. this._effect.setColor3(name, this._colors3[name]);
  60229. }
  60230. // Color4
  60231. for (name in this._colors4) {
  60232. var color = this._colors4[name];
  60233. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60234. }
  60235. // Vector2
  60236. for (name in this._vectors2) {
  60237. this._effect.setVector2(name, this._vectors2[name]);
  60238. }
  60239. // Vector3
  60240. for (name in this._vectors3) {
  60241. this._effect.setVector3(name, this._vectors3[name]);
  60242. }
  60243. // Matrix
  60244. for (name in this._matrices) {
  60245. this._effect.setMatrix(name, this._matrices[name]);
  60246. }
  60247. if (!this._texture) {
  60248. return;
  60249. }
  60250. if (this.isCube) {
  60251. for (var face = 0; face < 6; face++) {
  60252. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  60253. // VBOs
  60254. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60255. this._effect.setFloat("face", face);
  60256. // Clear
  60257. engine.clear(scene.clearColor, true, true, true);
  60258. // Draw order
  60259. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60260. // Mipmaps
  60261. if (face === 5) {
  60262. engine.generateMipMapsForCubemap(this._texture);
  60263. }
  60264. }
  60265. }
  60266. else {
  60267. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  60268. // VBOs
  60269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60270. // Clear
  60271. engine.clear(scene.clearColor, true, true, true);
  60272. // Draw order
  60273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60274. }
  60275. // Unbind
  60276. engine.unBindFramebuffer(this._texture, this.isCube);
  60277. if (this.onGenerated) {
  60278. this.onGenerated();
  60279. }
  60280. };
  60281. ProceduralTexture.prototype.clone = function () {
  60282. var textureSize = this.getSize();
  60283. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  60284. // Base texture
  60285. newTexture.hasAlpha = this.hasAlpha;
  60286. newTexture.level = this.level;
  60287. // RenderTarget Texture
  60288. newTexture.coordinatesMode = this.coordinatesMode;
  60289. return newTexture;
  60290. };
  60291. ProceduralTexture.prototype.dispose = function () {
  60292. var scene = this.getScene();
  60293. if (!scene) {
  60294. return;
  60295. }
  60296. var index = scene._proceduralTextures.indexOf(this);
  60297. if (index >= 0) {
  60298. scene._proceduralTextures.splice(index, 1);
  60299. }
  60300. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60301. if (vertexBuffer) {
  60302. vertexBuffer.dispose();
  60303. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60304. }
  60305. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  60306. this._indexBuffer = null;
  60307. }
  60308. _super.prototype.dispose.call(this);
  60309. };
  60310. return ProceduralTexture;
  60311. }(BABYLON.Texture));
  60312. BABYLON.ProceduralTexture = ProceduralTexture;
  60313. })(BABYLON || (BABYLON = {}));
  60314. //# sourceMappingURL=babylon.proceduralTexture.js.map
  60315. var BABYLON;
  60316. (function (BABYLON) {
  60317. var CustomProceduralTexture = /** @class */ (function (_super) {
  60318. __extends(CustomProceduralTexture, _super);
  60319. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  60320. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  60321. _this._animate = true;
  60322. _this._time = 0;
  60323. _this._texturePath = texturePath;
  60324. //Try to load json
  60325. _this.loadJson(texturePath);
  60326. _this.refreshRate = 1;
  60327. return _this;
  60328. }
  60329. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  60330. var _this = this;
  60331. var noConfigFile = function () {
  60332. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  60333. try {
  60334. _this.setFragment(_this._texturePath);
  60335. }
  60336. catch (ex) {
  60337. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  60338. }
  60339. };
  60340. var configFileUrl = jsonUrl + "/config.json";
  60341. var xhr = new XMLHttpRequest();
  60342. xhr.open("GET", configFileUrl, true);
  60343. xhr.addEventListener("load", function () {
  60344. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60345. try {
  60346. _this._config = JSON.parse(xhr.response);
  60347. _this.updateShaderUniforms();
  60348. _this.updateTextures();
  60349. _this.setFragment(_this._texturePath + "/custom");
  60350. _this._animate = _this._config.animate;
  60351. _this.refreshRate = _this._config.refreshrate;
  60352. }
  60353. catch (ex) {
  60354. noConfigFile();
  60355. }
  60356. }
  60357. else {
  60358. noConfigFile();
  60359. }
  60360. }, false);
  60361. xhr.addEventListener("error", function () {
  60362. noConfigFile();
  60363. }, false);
  60364. try {
  60365. xhr.send();
  60366. }
  60367. catch (ex) {
  60368. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  60369. }
  60370. };
  60371. CustomProceduralTexture.prototype.isReady = function () {
  60372. if (!_super.prototype.isReady.call(this)) {
  60373. return false;
  60374. }
  60375. for (var name in this._textures) {
  60376. var texture = this._textures[name];
  60377. if (!texture.isReady()) {
  60378. return false;
  60379. }
  60380. }
  60381. return true;
  60382. };
  60383. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60384. var scene = this.getScene();
  60385. if (this._animate && scene) {
  60386. this._time += scene.getAnimationRatio() * 0.03;
  60387. this.updateShaderUniforms();
  60388. }
  60389. _super.prototype.render.call(this, useCameraPostProcess);
  60390. };
  60391. CustomProceduralTexture.prototype.updateTextures = function () {
  60392. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  60393. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  60394. }
  60395. };
  60396. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  60397. if (this._config) {
  60398. for (var j = 0; j < this._config.uniforms.length; j++) {
  60399. var uniform = this._config.uniforms[j];
  60400. switch (uniform.type) {
  60401. case "float":
  60402. this.setFloat(uniform.name, uniform.value);
  60403. break;
  60404. case "color3":
  60405. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  60406. break;
  60407. case "color4":
  60408. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  60409. break;
  60410. case "vector2":
  60411. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  60412. break;
  60413. case "vector3":
  60414. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  60415. break;
  60416. }
  60417. }
  60418. }
  60419. this.setFloat("time", this._time);
  60420. };
  60421. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  60422. get: function () {
  60423. return this._animate;
  60424. },
  60425. set: function (value) {
  60426. this._animate = value;
  60427. },
  60428. enumerable: true,
  60429. configurable: true
  60430. });
  60431. return CustomProceduralTexture;
  60432. }(BABYLON.ProceduralTexture));
  60433. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  60434. })(BABYLON || (BABYLON = {}));
  60435. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  60436. var BABYLON;
  60437. (function (BABYLON) {
  60438. var FreeCameraGamepadInput = /** @class */ (function () {
  60439. function FreeCameraGamepadInput() {
  60440. this.gamepadAngularSensibility = 200;
  60441. this.gamepadMoveSensibility = 40;
  60442. // private members
  60443. this._cameraTransform = BABYLON.Matrix.Identity();
  60444. this._deltaTransform = BABYLON.Vector3.Zero();
  60445. this._vector3 = BABYLON.Vector3.Zero();
  60446. this._vector2 = BABYLON.Vector2.Zero();
  60447. }
  60448. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60449. var _this = this;
  60450. var manager = this.camera.getScene().gamepadManager;
  60451. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60452. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60453. // prioritize XBOX gamepads.
  60454. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60455. _this.gamepad = gamepad;
  60456. }
  60457. }
  60458. });
  60459. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60460. if (_this.gamepad === gamepad) {
  60461. _this.gamepad = null;
  60462. }
  60463. });
  60464. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60465. };
  60466. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  60467. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60468. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60469. this.gamepad = null;
  60470. };
  60471. FreeCameraGamepadInput.prototype.checkInputs = function () {
  60472. if (this.gamepad && this.gamepad.leftStick) {
  60473. var camera = this.camera;
  60474. var LSValues = this.gamepad.leftStick;
  60475. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  60476. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60477. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  60478. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  60479. var RSValues = this.gamepad.rightStick;
  60480. if (RSValues) {
  60481. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  60482. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  60483. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  60484. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  60485. }
  60486. else {
  60487. RSValues = { x: 0, y: 0 };
  60488. }
  60489. if (!camera.rotationQuaternion) {
  60490. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  60491. }
  60492. else {
  60493. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  60494. }
  60495. var speed = camera._computeLocalCameraSpeed() * 50.0;
  60496. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  60497. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  60498. camera.cameraDirection.addInPlace(this._deltaTransform);
  60499. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  60500. camera.cameraRotation.addInPlace(this._vector2);
  60501. }
  60502. };
  60503. FreeCameraGamepadInput.prototype.getClassName = function () {
  60504. return "FreeCameraGamepadInput";
  60505. };
  60506. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  60507. return "gamepad";
  60508. };
  60509. __decorate([
  60510. BABYLON.serialize()
  60511. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  60512. __decorate([
  60513. BABYLON.serialize()
  60514. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60515. return FreeCameraGamepadInput;
  60516. }());
  60517. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  60518. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  60519. })(BABYLON || (BABYLON = {}));
  60520. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  60521. var BABYLON;
  60522. (function (BABYLON) {
  60523. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  60524. function ArcRotateCameraGamepadInput() {
  60525. this.gamepadRotationSensibility = 80;
  60526. this.gamepadMoveSensibility = 40;
  60527. }
  60528. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60529. var _this = this;
  60530. var manager = this.camera.getScene().gamepadManager;
  60531. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60532. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60533. // prioritize XBOX gamepads.
  60534. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60535. _this.gamepad = gamepad;
  60536. }
  60537. }
  60538. });
  60539. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60540. if (_this.gamepad === gamepad) {
  60541. _this.gamepad = null;
  60542. }
  60543. });
  60544. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60545. };
  60546. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  60547. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60548. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60549. this.gamepad = null;
  60550. };
  60551. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  60552. if (this.gamepad) {
  60553. var camera = this.camera;
  60554. var RSValues = this.gamepad.rightStick;
  60555. if (RSValues) {
  60556. if (RSValues.x != 0) {
  60557. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  60558. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  60559. camera.inertialAlphaOffset += normalizedRX;
  60560. }
  60561. }
  60562. if (RSValues.y != 0) {
  60563. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  60564. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  60565. camera.inertialBetaOffset += normalizedRY;
  60566. }
  60567. }
  60568. }
  60569. var LSValues = this.gamepad.leftStick;
  60570. if (LSValues && LSValues.y != 0) {
  60571. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60572. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  60573. this.camera.inertialRadiusOffset -= normalizedLY;
  60574. }
  60575. }
  60576. }
  60577. };
  60578. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  60579. return "ArcRotateCameraGamepadInput";
  60580. };
  60581. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  60582. return "gamepad";
  60583. };
  60584. __decorate([
  60585. BABYLON.serialize()
  60586. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  60587. __decorate([
  60588. BABYLON.serialize()
  60589. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60590. return ArcRotateCameraGamepadInput;
  60591. }());
  60592. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  60593. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  60594. })(BABYLON || (BABYLON = {}));
  60595. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  60596. var BABYLON;
  60597. (function (BABYLON) {
  60598. var GamepadManager = /** @class */ (function () {
  60599. function GamepadManager(_scene) {
  60600. var _this = this;
  60601. this._scene = _scene;
  60602. this._babylonGamepads = [];
  60603. this._oneGamepadConnected = false;
  60604. this._isMonitoring = false;
  60605. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  60606. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60607. this._gamepadEventSupported = false;
  60608. }
  60609. else {
  60610. this._gamepadEventSupported = 'GamepadEvent' in window;
  60611. this._gamepadSupport = (navigator.getGamepads ||
  60612. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  60613. }
  60614. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  60615. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  60616. for (var i in _this._babylonGamepads) {
  60617. var gamepad = _this._babylonGamepads[i];
  60618. if (gamepad && gamepad._isConnected) {
  60619. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  60620. }
  60621. }
  60622. });
  60623. this._onGamepadConnectedEvent = function (evt) {
  60624. var gamepad = evt.gamepad;
  60625. if (gamepad.index in _this._babylonGamepads) {
  60626. if (_this._babylonGamepads[gamepad.index].isConnected) {
  60627. return;
  60628. }
  60629. }
  60630. var newGamepad;
  60631. if (_this._babylonGamepads[gamepad.index]) {
  60632. newGamepad = _this._babylonGamepads[gamepad.index];
  60633. newGamepad.browserGamepad = gamepad;
  60634. newGamepad._isConnected = true;
  60635. }
  60636. else {
  60637. newGamepad = _this._addNewGamepad(gamepad);
  60638. }
  60639. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60640. _this._startMonitoringGamepads();
  60641. };
  60642. this._onGamepadDisconnectedEvent = function (evt) {
  60643. var gamepad = evt.gamepad;
  60644. // Remove the gamepad from the list of gamepads to monitor.
  60645. for (var i in _this._babylonGamepads) {
  60646. if (_this._babylonGamepads[i].index === gamepad.index) {
  60647. var disconnectedGamepad = _this._babylonGamepads[i];
  60648. disconnectedGamepad._isConnected = false;
  60649. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  60650. break;
  60651. }
  60652. }
  60653. };
  60654. if (this._gamepadSupport) {
  60655. //first add already-connected gamepads
  60656. this._updateGamepadObjects();
  60657. if (this._babylonGamepads.length) {
  60658. this._startMonitoringGamepads();
  60659. }
  60660. // Checking if the gamepad connected event is supported (like in Firefox)
  60661. if (this._gamepadEventSupported) {
  60662. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  60663. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  60664. }
  60665. else {
  60666. this._startMonitoringGamepads();
  60667. }
  60668. }
  60669. }
  60670. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  60671. get: function () {
  60672. return this._babylonGamepads;
  60673. },
  60674. enumerable: true,
  60675. configurable: true
  60676. });
  60677. GamepadManager.prototype.getGamepadByType = function (type) {
  60678. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  60679. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  60680. var gamepad = _a[_i];
  60681. if (gamepad && gamepad.type === type) {
  60682. return gamepad;
  60683. }
  60684. }
  60685. return null;
  60686. };
  60687. GamepadManager.prototype.dispose = function () {
  60688. if (this._gamepadEventSupported) {
  60689. if (this._onGamepadConnectedEvent) {
  60690. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  60691. }
  60692. if (this._onGamepadDisconnectedEvent) {
  60693. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  60694. }
  60695. this._onGamepadConnectedEvent = null;
  60696. this._onGamepadDisconnectedEvent = null;
  60697. }
  60698. this._babylonGamepads.forEach(function (gamepad) {
  60699. gamepad.dispose();
  60700. });
  60701. this.onGamepadConnectedObservable.clear();
  60702. this.onGamepadDisconnectedObservable.clear();
  60703. this._oneGamepadConnected = false;
  60704. this._stopMonitoringGamepads();
  60705. this._babylonGamepads = [];
  60706. };
  60707. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  60708. if (!this._oneGamepadConnected) {
  60709. this._oneGamepadConnected = true;
  60710. }
  60711. var newGamepad;
  60712. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  60713. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  60714. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  60715. }
  60716. else if (gamepad.pose) {
  60717. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  60718. }
  60719. else {
  60720. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  60721. }
  60722. this._babylonGamepads[newGamepad.index] = newGamepad;
  60723. return newGamepad;
  60724. };
  60725. GamepadManager.prototype._startMonitoringGamepads = function () {
  60726. if (!this._isMonitoring) {
  60727. this._isMonitoring = true;
  60728. //back-comp
  60729. if (!this._scene) {
  60730. this._checkGamepadsStatus();
  60731. }
  60732. }
  60733. };
  60734. GamepadManager.prototype._stopMonitoringGamepads = function () {
  60735. this._isMonitoring = false;
  60736. };
  60737. GamepadManager.prototype._checkGamepadsStatus = function () {
  60738. var _this = this;
  60739. // Hack to be compatible Chrome
  60740. this._updateGamepadObjects();
  60741. for (var i in this._babylonGamepads) {
  60742. var gamepad = this._babylonGamepads[i];
  60743. if (!gamepad || !gamepad.isConnected) {
  60744. continue;
  60745. }
  60746. gamepad.update();
  60747. }
  60748. if (this._isMonitoring && !this._scene) {
  60749. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  60750. }
  60751. };
  60752. // This function is called only on Chrome, which does not properly support
  60753. // connection/disconnection events and forces you to recopy again the gamepad object
  60754. GamepadManager.prototype._updateGamepadObjects = function () {
  60755. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  60756. for (var i = 0; i < gamepads.length; i++) {
  60757. if (gamepads[i]) {
  60758. if (!this._babylonGamepads[gamepads[i].index]) {
  60759. var newGamepad = this._addNewGamepad(gamepads[i]);
  60760. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60761. }
  60762. else {
  60763. // Forced to copy again this object for Chrome for unknown reason
  60764. this._babylonGamepads[i].browserGamepad = gamepads[i];
  60765. if (!this._babylonGamepads[i].isConnected) {
  60766. this._babylonGamepads[i]._isConnected = true;
  60767. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  60768. }
  60769. }
  60770. }
  60771. }
  60772. };
  60773. return GamepadManager;
  60774. }());
  60775. BABYLON.GamepadManager = GamepadManager;
  60776. })(BABYLON || (BABYLON = {}));
  60777. //# sourceMappingURL=babylon.gamepadManager.js.map
  60778. var BABYLON;
  60779. (function (BABYLON) {
  60780. var StickValues = /** @class */ (function () {
  60781. function StickValues(x, y) {
  60782. this.x = x;
  60783. this.y = y;
  60784. }
  60785. return StickValues;
  60786. }());
  60787. BABYLON.StickValues = StickValues;
  60788. var Gamepad = /** @class */ (function () {
  60789. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  60790. if (leftStickX === void 0) { leftStickX = 0; }
  60791. if (leftStickY === void 0) { leftStickY = 1; }
  60792. if (rightStickX === void 0) { rightStickX = 2; }
  60793. if (rightStickY === void 0) { rightStickY = 3; }
  60794. this.id = id;
  60795. this.index = index;
  60796. this.browserGamepad = browserGamepad;
  60797. this._isConnected = true;
  60798. this._invertLeftStickY = false;
  60799. this.type = Gamepad.GAMEPAD;
  60800. this._leftStickAxisX = leftStickX;
  60801. this._leftStickAxisY = leftStickY;
  60802. this._rightStickAxisX = rightStickX;
  60803. this._rightStickAxisY = rightStickY;
  60804. if (this.browserGamepad.axes.length >= 2) {
  60805. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60806. }
  60807. if (this.browserGamepad.axes.length >= 4) {
  60808. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60809. }
  60810. }
  60811. Object.defineProperty(Gamepad.prototype, "isConnected", {
  60812. get: function () {
  60813. return this._isConnected;
  60814. },
  60815. enumerable: true,
  60816. configurable: true
  60817. });
  60818. Gamepad.prototype.onleftstickchanged = function (callback) {
  60819. this._onleftstickchanged = callback;
  60820. };
  60821. Gamepad.prototype.onrightstickchanged = function (callback) {
  60822. this._onrightstickchanged = callback;
  60823. };
  60824. Object.defineProperty(Gamepad.prototype, "leftStick", {
  60825. get: function () {
  60826. return this._leftStick;
  60827. },
  60828. set: function (newValues) {
  60829. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  60830. this._onleftstickchanged(newValues);
  60831. }
  60832. this._leftStick = newValues;
  60833. },
  60834. enumerable: true,
  60835. configurable: true
  60836. });
  60837. Object.defineProperty(Gamepad.prototype, "rightStick", {
  60838. get: function () {
  60839. return this._rightStick;
  60840. },
  60841. set: function (newValues) {
  60842. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  60843. this._onrightstickchanged(newValues);
  60844. }
  60845. this._rightStick = newValues;
  60846. },
  60847. enumerable: true,
  60848. configurable: true
  60849. });
  60850. Gamepad.prototype.update = function () {
  60851. if (this._leftStick) {
  60852. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60853. if (this._invertLeftStickY) {
  60854. this.leftStick.y *= -1;
  60855. }
  60856. }
  60857. if (this._rightStick) {
  60858. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60859. }
  60860. };
  60861. Gamepad.prototype.dispose = function () {
  60862. };
  60863. Gamepad.GAMEPAD = 0;
  60864. Gamepad.GENERIC = 1;
  60865. Gamepad.XBOX = 2;
  60866. Gamepad.POSE_ENABLED = 3;
  60867. return Gamepad;
  60868. }());
  60869. BABYLON.Gamepad = Gamepad;
  60870. var GenericPad = /** @class */ (function (_super) {
  60871. __extends(GenericPad, _super);
  60872. function GenericPad(id, index, browserGamepad) {
  60873. var _this = _super.call(this, id, index, browserGamepad) || this;
  60874. _this.onButtonDownObservable = new BABYLON.Observable();
  60875. _this.onButtonUpObservable = new BABYLON.Observable();
  60876. _this.type = Gamepad.GENERIC;
  60877. _this._buttons = new Array(browserGamepad.buttons.length);
  60878. return _this;
  60879. }
  60880. GenericPad.prototype.onbuttondown = function (callback) {
  60881. this._onbuttondown = callback;
  60882. };
  60883. GenericPad.prototype.onbuttonup = function (callback) {
  60884. this._onbuttonup = callback;
  60885. };
  60886. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  60887. if (newValue !== currentValue) {
  60888. if (newValue === 1) {
  60889. if (this._onbuttondown) {
  60890. this._onbuttondown(buttonIndex);
  60891. }
  60892. this.onButtonDownObservable.notifyObservers(buttonIndex);
  60893. }
  60894. if (newValue === 0) {
  60895. if (this._onbuttonup) {
  60896. this._onbuttonup(buttonIndex);
  60897. }
  60898. this.onButtonUpObservable.notifyObservers(buttonIndex);
  60899. }
  60900. }
  60901. return newValue;
  60902. };
  60903. GenericPad.prototype.update = function () {
  60904. _super.prototype.update.call(this);
  60905. for (var index = 0; index < this._buttons.length; index++) {
  60906. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  60907. }
  60908. };
  60909. GenericPad.prototype.dispose = function () {
  60910. _super.prototype.dispose.call(this);
  60911. this.onButtonDownObservable.clear();
  60912. this.onButtonUpObservable.clear();
  60913. };
  60914. return GenericPad;
  60915. }(Gamepad));
  60916. BABYLON.GenericPad = GenericPad;
  60917. })(BABYLON || (BABYLON = {}));
  60918. //# sourceMappingURL=babylon.gamepad.js.map
  60919. var BABYLON;
  60920. (function (BABYLON) {
  60921. var Xbox360Button;
  60922. (function (Xbox360Button) {
  60923. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  60924. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  60925. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  60926. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  60927. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  60928. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  60929. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  60930. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  60931. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  60932. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  60933. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  60934. var Xbox360Dpad;
  60935. (function (Xbox360Dpad) {
  60936. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  60937. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  60938. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  60939. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  60940. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  60941. var Xbox360Pad = /** @class */ (function (_super) {
  60942. __extends(Xbox360Pad, _super);
  60943. function Xbox360Pad(id, index, gamepad, xboxOne) {
  60944. if (xboxOne === void 0) { xboxOne = false; }
  60945. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  60946. _this._leftTrigger = 0;
  60947. _this._rightTrigger = 0;
  60948. _this.onButtonDownObservable = new BABYLON.Observable();
  60949. _this.onButtonUpObservable = new BABYLON.Observable();
  60950. _this.onPadDownObservable = new BABYLON.Observable();
  60951. _this.onPadUpObservable = new BABYLON.Observable();
  60952. _this._buttonA = 0;
  60953. _this._buttonB = 0;
  60954. _this._buttonX = 0;
  60955. _this._buttonY = 0;
  60956. _this._buttonBack = 0;
  60957. _this._buttonStart = 0;
  60958. _this._buttonLB = 0;
  60959. _this._buttonRB = 0;
  60960. _this._buttonLeftStick = 0;
  60961. _this._buttonRightStick = 0;
  60962. _this._dPadUp = 0;
  60963. _this._dPadDown = 0;
  60964. _this._dPadLeft = 0;
  60965. _this._dPadRight = 0;
  60966. _this._isXboxOnePad = false;
  60967. _this.type = BABYLON.Gamepad.XBOX;
  60968. _this._isXboxOnePad = xboxOne;
  60969. return _this;
  60970. }
  60971. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  60972. this._onlefttriggerchanged = callback;
  60973. };
  60974. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  60975. this._onrighttriggerchanged = callback;
  60976. };
  60977. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  60978. get: function () {
  60979. return this._leftTrigger;
  60980. },
  60981. set: function (newValue) {
  60982. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  60983. this._onlefttriggerchanged(newValue);
  60984. }
  60985. this._leftTrigger = newValue;
  60986. },
  60987. enumerable: true,
  60988. configurable: true
  60989. });
  60990. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  60991. get: function () {
  60992. return this._rightTrigger;
  60993. },
  60994. set: function (newValue) {
  60995. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  60996. this._onrighttriggerchanged(newValue);
  60997. }
  60998. this._rightTrigger = newValue;
  60999. },
  61000. enumerable: true,
  61001. configurable: true
  61002. });
  61003. Xbox360Pad.prototype.onbuttondown = function (callback) {
  61004. this._onbuttondown = callback;
  61005. };
  61006. Xbox360Pad.prototype.onbuttonup = function (callback) {
  61007. this._onbuttonup = callback;
  61008. };
  61009. Xbox360Pad.prototype.ondpaddown = function (callback) {
  61010. this._ondpaddown = callback;
  61011. };
  61012. Xbox360Pad.prototype.ondpadup = function (callback) {
  61013. this._ondpadup = callback;
  61014. };
  61015. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  61016. if (newValue !== currentValue) {
  61017. if (newValue === 1) {
  61018. if (this._onbuttondown) {
  61019. this._onbuttondown(buttonType);
  61020. }
  61021. this.onButtonDownObservable.notifyObservers(buttonType);
  61022. }
  61023. if (newValue === 0) {
  61024. if (this._onbuttonup) {
  61025. this._onbuttonup(buttonType);
  61026. }
  61027. this.onButtonUpObservable.notifyObservers(buttonType);
  61028. }
  61029. }
  61030. return newValue;
  61031. };
  61032. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  61033. if (newValue !== currentValue) {
  61034. if (newValue === 1) {
  61035. if (this._ondpaddown) {
  61036. this._ondpaddown(buttonType);
  61037. }
  61038. this.onPadDownObservable.notifyObservers(buttonType);
  61039. }
  61040. if (newValue === 0) {
  61041. if (this._ondpadup) {
  61042. this._ondpadup(buttonType);
  61043. }
  61044. this.onPadUpObservable.notifyObservers(buttonType);
  61045. }
  61046. }
  61047. return newValue;
  61048. };
  61049. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  61050. get: function () {
  61051. return this._buttonA;
  61052. },
  61053. set: function (value) {
  61054. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  61055. },
  61056. enumerable: true,
  61057. configurable: true
  61058. });
  61059. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  61060. get: function () {
  61061. return this._buttonB;
  61062. },
  61063. set: function (value) {
  61064. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  61065. },
  61066. enumerable: true,
  61067. configurable: true
  61068. });
  61069. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  61070. get: function () {
  61071. return this._buttonX;
  61072. },
  61073. set: function (value) {
  61074. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  61075. },
  61076. enumerable: true,
  61077. configurable: true
  61078. });
  61079. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  61080. get: function () {
  61081. return this._buttonY;
  61082. },
  61083. set: function (value) {
  61084. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  61085. },
  61086. enumerable: true,
  61087. configurable: true
  61088. });
  61089. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  61090. get: function () {
  61091. return this._buttonStart;
  61092. },
  61093. set: function (value) {
  61094. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  61095. },
  61096. enumerable: true,
  61097. configurable: true
  61098. });
  61099. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  61100. get: function () {
  61101. return this._buttonBack;
  61102. },
  61103. set: function (value) {
  61104. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  61105. },
  61106. enumerable: true,
  61107. configurable: true
  61108. });
  61109. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  61110. get: function () {
  61111. return this._buttonLB;
  61112. },
  61113. set: function (value) {
  61114. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  61115. },
  61116. enumerable: true,
  61117. configurable: true
  61118. });
  61119. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  61120. get: function () {
  61121. return this._buttonRB;
  61122. },
  61123. set: function (value) {
  61124. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  61125. },
  61126. enumerable: true,
  61127. configurable: true
  61128. });
  61129. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  61130. get: function () {
  61131. return this._buttonLeftStick;
  61132. },
  61133. set: function (value) {
  61134. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  61135. },
  61136. enumerable: true,
  61137. configurable: true
  61138. });
  61139. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  61140. get: function () {
  61141. return this._buttonRightStick;
  61142. },
  61143. set: function (value) {
  61144. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  61145. },
  61146. enumerable: true,
  61147. configurable: true
  61148. });
  61149. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  61150. get: function () {
  61151. return this._dPadUp;
  61152. },
  61153. set: function (value) {
  61154. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  61155. },
  61156. enumerable: true,
  61157. configurable: true
  61158. });
  61159. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  61160. get: function () {
  61161. return this._dPadDown;
  61162. },
  61163. set: function (value) {
  61164. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  61165. },
  61166. enumerable: true,
  61167. configurable: true
  61168. });
  61169. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  61170. get: function () {
  61171. return this._dPadLeft;
  61172. },
  61173. set: function (value) {
  61174. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  61175. },
  61176. enumerable: true,
  61177. configurable: true
  61178. });
  61179. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  61180. get: function () {
  61181. return this._dPadRight;
  61182. },
  61183. set: function (value) {
  61184. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  61185. },
  61186. enumerable: true,
  61187. configurable: true
  61188. });
  61189. Xbox360Pad.prototype.update = function () {
  61190. _super.prototype.update.call(this);
  61191. if (this._isXboxOnePad) {
  61192. this.buttonA = this.browserGamepad.buttons[0].value;
  61193. this.buttonB = this.browserGamepad.buttons[1].value;
  61194. this.buttonX = this.browserGamepad.buttons[2].value;
  61195. this.buttonY = this.browserGamepad.buttons[3].value;
  61196. this.buttonLB = this.browserGamepad.buttons[4].value;
  61197. this.buttonRB = this.browserGamepad.buttons[5].value;
  61198. this.leftTrigger = this.browserGamepad.axes[2];
  61199. this.rightTrigger = this.browserGamepad.axes[5];
  61200. this.buttonBack = this.browserGamepad.buttons[9].value;
  61201. this.buttonStart = this.browserGamepad.buttons[8].value;
  61202. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  61203. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  61204. this.dPadUp = this.browserGamepad.buttons[11].value;
  61205. this.dPadDown = this.browserGamepad.buttons[12].value;
  61206. this.dPadLeft = this.browserGamepad.buttons[13].value;
  61207. this.dPadRight = this.browserGamepad.buttons[14].value;
  61208. }
  61209. else {
  61210. this.buttonA = this.browserGamepad.buttons[0].value;
  61211. this.buttonB = this.browserGamepad.buttons[1].value;
  61212. this.buttonX = this.browserGamepad.buttons[2].value;
  61213. this.buttonY = this.browserGamepad.buttons[3].value;
  61214. this.buttonLB = this.browserGamepad.buttons[4].value;
  61215. this.buttonRB = this.browserGamepad.buttons[5].value;
  61216. this.leftTrigger = this.browserGamepad.buttons[6].value;
  61217. this.rightTrigger = this.browserGamepad.buttons[7].value;
  61218. this.buttonBack = this.browserGamepad.buttons[8].value;
  61219. this.buttonStart = this.browserGamepad.buttons[9].value;
  61220. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  61221. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  61222. this.dPadUp = this.browserGamepad.buttons[12].value;
  61223. this.dPadDown = this.browserGamepad.buttons[13].value;
  61224. this.dPadLeft = this.browserGamepad.buttons[14].value;
  61225. this.dPadRight = this.browserGamepad.buttons[15].value;
  61226. }
  61227. };
  61228. Xbox360Pad.prototype.dispose = function () {
  61229. _super.prototype.dispose.call(this);
  61230. this.onButtonDownObservable.clear();
  61231. this.onButtonUpObservable.clear();
  61232. this.onPadDownObservable.clear();
  61233. this.onPadUpObservable.clear();
  61234. };
  61235. return Xbox360Pad;
  61236. }(BABYLON.Gamepad));
  61237. BABYLON.Xbox360Pad = Xbox360Pad;
  61238. })(BABYLON || (BABYLON = {}));
  61239. //# sourceMappingURL=babylon.xboxGamepad.js.map
  61240. var BABYLON;
  61241. (function (BABYLON) {
  61242. var PoseEnabledControllerType;
  61243. (function (PoseEnabledControllerType) {
  61244. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  61245. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  61246. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  61247. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  61248. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  61249. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  61250. var PoseEnabledControllerHelper = /** @class */ (function () {
  61251. function PoseEnabledControllerHelper() {
  61252. }
  61253. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  61254. // Oculus Touch
  61255. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  61256. return new BABYLON.OculusTouchController(vrGamepad);
  61257. }
  61258. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  61259. return new BABYLON.WindowsMotionController(vrGamepad);
  61260. }
  61261. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  61262. return new BABYLON.ViveController(vrGamepad);
  61263. }
  61264. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  61265. return new BABYLON.GearVRController(vrGamepad);
  61266. }
  61267. else {
  61268. return new BABYLON.GenericController(vrGamepad);
  61269. }
  61270. };
  61271. return PoseEnabledControllerHelper;
  61272. }());
  61273. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  61274. var PoseEnabledController = /** @class */ (function (_super) {
  61275. __extends(PoseEnabledController, _super);
  61276. function PoseEnabledController(browserGamepad) {
  61277. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  61278. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  61279. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  61280. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  61281. // Represents device position and rotation in babylon space
  61282. _this.devicePosition = BABYLON.Vector3.Zero();
  61283. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61284. _this.deviceScaleFactor = 1;
  61285. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  61286. _this._deviceToWorld = BABYLON.Matrix.Identity();
  61287. _this._workingMatrix = BABYLON.Matrix.Identity();
  61288. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  61289. _this.controllerType = PoseEnabledControllerType.GENERIC;
  61290. _this.position = BABYLON.Vector3.Zero();
  61291. _this.rotationQuaternion = new BABYLON.Quaternion();
  61292. _this._calculatedPosition = BABYLON.Vector3.Zero();
  61293. _this._calculatedRotation = new BABYLON.Quaternion();
  61294. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  61295. return _this;
  61296. }
  61297. PoseEnabledController.prototype.update = function () {
  61298. _super.prototype.update.call(this);
  61299. var pose = this.browserGamepad.pose;
  61300. this.updateFromDevice(pose);
  61301. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  61302. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  61303. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  61304. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  61305. if (this._mesh) {
  61306. this._mesh.position.copyFrom(this.devicePosition);
  61307. if (this._mesh.rotationQuaternion) {
  61308. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61309. }
  61310. }
  61311. };
  61312. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  61313. if (poseData) {
  61314. this.rawPose = poseData;
  61315. if (poseData.position) {
  61316. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  61317. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  61318. this._deviceRoomPosition.z *= -1;
  61319. }
  61320. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  61321. this._calculatedPosition.addInPlace(this.position);
  61322. }
  61323. var pose = this.rawPose;
  61324. if (poseData.orientation && pose.orientation) {
  61325. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  61326. if (this._mesh) {
  61327. if (this._mesh.getScene().useRightHandedSystem) {
  61328. this._deviceRoomRotationQuaternion.z *= -1;
  61329. this._deviceRoomRotationQuaternion.w *= -1;
  61330. }
  61331. else {
  61332. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  61333. }
  61334. }
  61335. // if the camera is set, rotate to the camera's rotation
  61336. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  61337. }
  61338. }
  61339. };
  61340. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  61341. if (this._mesh) {
  61342. this._mesh.parent = null;
  61343. }
  61344. this._mesh = mesh;
  61345. if (this._poseControlledCamera) {
  61346. this._mesh.parent = this._poseControlledCamera;
  61347. }
  61348. if (!this._mesh.rotationQuaternion) {
  61349. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  61350. }
  61351. };
  61352. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  61353. this._poseControlledCamera = camera;
  61354. if (this._mesh) {
  61355. this._mesh.parent = this._poseControlledCamera;
  61356. }
  61357. };
  61358. PoseEnabledController.prototype.dispose = function () {
  61359. if (this._mesh) {
  61360. this._mesh.dispose();
  61361. }
  61362. this._mesh = null;
  61363. _super.prototype.dispose.call(this);
  61364. };
  61365. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  61366. get: function () {
  61367. return this._mesh;
  61368. },
  61369. enumerable: true,
  61370. configurable: true
  61371. });
  61372. PoseEnabledController.prototype.getForwardRay = function (length) {
  61373. if (length === void 0) { length = 100; }
  61374. if (!this.mesh) {
  61375. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  61376. }
  61377. var m = this.mesh.getWorldMatrix();
  61378. var origin = m.getTranslation();
  61379. var forward = new BABYLON.Vector3(0, 0, -1);
  61380. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61381. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61382. return new BABYLON.Ray(origin, direction, length);
  61383. };
  61384. return PoseEnabledController;
  61385. }(BABYLON.Gamepad));
  61386. BABYLON.PoseEnabledController = PoseEnabledController;
  61387. })(BABYLON || (BABYLON = {}));
  61388. //# sourceMappingURL=babylon.poseEnabledController.js.map
  61389. var BABYLON;
  61390. (function (BABYLON) {
  61391. var WebVRController = /** @class */ (function (_super) {
  61392. __extends(WebVRController, _super);
  61393. function WebVRController(vrGamepad) {
  61394. var _this = _super.call(this, vrGamepad) || this;
  61395. // Observables
  61396. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  61397. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  61398. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  61399. _this.onPadStateChangedObservable = new BABYLON.Observable();
  61400. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  61401. _this.pad = { x: 0, y: 0 };
  61402. // avoid GC, store state in a tmp object
  61403. _this._changes = {
  61404. pressChanged: false,
  61405. touchChanged: false,
  61406. valueChanged: false,
  61407. changed: false
  61408. };
  61409. _this._buttons = new Array(vrGamepad.buttons.length);
  61410. _this.hand = vrGamepad.hand;
  61411. return _this;
  61412. }
  61413. WebVRController.prototype.onButtonStateChange = function (callback) {
  61414. this._onButtonStateChange = callback;
  61415. };
  61416. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  61417. get: function () {
  61418. return this._defaultModel;
  61419. },
  61420. enumerable: true,
  61421. configurable: true
  61422. });
  61423. WebVRController.prototype.update = function () {
  61424. _super.prototype.update.call(this);
  61425. for (var index = 0; index < this._buttons.length; index++) {
  61426. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  61427. }
  61428. ;
  61429. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  61430. this.pad.x = this.leftStick.x;
  61431. this.pad.y = this.leftStick.y;
  61432. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  61433. }
  61434. };
  61435. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  61436. if (!newState) {
  61437. newState = {
  61438. pressed: false,
  61439. touched: false,
  61440. value: 0
  61441. };
  61442. }
  61443. if (!currentState) {
  61444. this._buttons[buttonIndex] = {
  61445. pressed: newState.pressed,
  61446. touched: newState.touched,
  61447. value: newState.value
  61448. };
  61449. return;
  61450. }
  61451. this._checkChanges(newState, currentState);
  61452. if (this._changes.changed) {
  61453. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  61454. this.handleButtonChange(buttonIndex, newState, this._changes);
  61455. }
  61456. this._buttons[buttonIndex].pressed = newState.pressed;
  61457. this._buttons[buttonIndex].touched = newState.touched;
  61458. // oculus triggers are never 0, thou not touched.
  61459. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  61460. };
  61461. WebVRController.prototype._checkChanges = function (newState, currentState) {
  61462. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  61463. this._changes.touchChanged = newState.touched !== currentState.touched;
  61464. this._changes.valueChanged = newState.value !== currentState.value;
  61465. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  61466. return this._changes;
  61467. };
  61468. WebVRController.prototype.dispose = function () {
  61469. _super.prototype.dispose.call(this);
  61470. this.onTriggerStateChangedObservable.clear();
  61471. this.onMainButtonStateChangedObservable.clear();
  61472. this.onSecondaryButtonStateChangedObservable.clear();
  61473. this.onPadStateChangedObservable.clear();
  61474. this.onPadValuesChangedObservable.clear();
  61475. };
  61476. return WebVRController;
  61477. }(BABYLON.PoseEnabledController));
  61478. BABYLON.WebVRController = WebVRController;
  61479. })(BABYLON || (BABYLON = {}));
  61480. //# sourceMappingURL=babylon.webVRController.js.map
  61481. var BABYLON;
  61482. (function (BABYLON) {
  61483. var OculusTouchController = /** @class */ (function (_super) {
  61484. __extends(OculusTouchController, _super);
  61485. function OculusTouchController(vrGamepad) {
  61486. var _this = _super.call(this, vrGamepad) || this;
  61487. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  61488. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  61489. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  61490. return _this;
  61491. }
  61492. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61493. var _this = this;
  61494. var meshName;
  61495. // Hand
  61496. if (this.hand === 'left') {
  61497. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  61498. }
  61499. else {
  61500. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  61501. }
  61502. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  61503. /*
  61504. Parent Mesh name: oculus_touch_left
  61505. - body
  61506. - trigger
  61507. - thumbstick
  61508. - grip
  61509. - button_y
  61510. - button_x
  61511. - button_enter
  61512. */
  61513. _this._defaultModel = newMeshes[1];
  61514. _this.attachToMesh(_this._defaultModel);
  61515. if (meshLoaded) {
  61516. meshLoaded(_this._defaultModel);
  61517. }
  61518. });
  61519. };
  61520. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  61521. // helper getters for left and right hand.
  61522. get: function () {
  61523. if (this.hand === 'right') {
  61524. return this.onMainButtonStateChangedObservable;
  61525. }
  61526. else {
  61527. throw new Error('No A button on left hand');
  61528. }
  61529. },
  61530. enumerable: true,
  61531. configurable: true
  61532. });
  61533. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  61534. get: function () {
  61535. if (this.hand === 'right') {
  61536. return this.onSecondaryButtonStateChangedObservable;
  61537. }
  61538. else {
  61539. throw new Error('No B button on left hand');
  61540. }
  61541. },
  61542. enumerable: true,
  61543. configurable: true
  61544. });
  61545. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  61546. get: function () {
  61547. if (this.hand === 'left') {
  61548. return this.onMainButtonStateChangedObservable;
  61549. }
  61550. else {
  61551. throw new Error('No X button on right hand');
  61552. }
  61553. },
  61554. enumerable: true,
  61555. configurable: true
  61556. });
  61557. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  61558. get: function () {
  61559. if (this.hand === 'left') {
  61560. return this.onSecondaryButtonStateChangedObservable;
  61561. }
  61562. else {
  61563. throw new Error('No Y button on right hand');
  61564. }
  61565. },
  61566. enumerable: true,
  61567. configurable: true
  61568. });
  61569. /*
  61570. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  61571. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  61572. 2) secondary trigger (same)
  61573. 3) A (right) X (left), touch, pressed = value
  61574. 4) B / Y
  61575. 5) thumb rest
  61576. */
  61577. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61578. var notifyObject = state; //{ state: state, changes: changes };
  61579. var triggerDirection = this.hand === 'right' ? -1 : 1;
  61580. switch (buttonIdx) {
  61581. case 0:
  61582. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61583. return;
  61584. case 1:// index trigger
  61585. if (this._defaultModel) {
  61586. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  61587. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  61588. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  61589. }
  61590. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61591. return;
  61592. case 2:// secondary trigger
  61593. if (this._defaultModel) {
  61594. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  61595. }
  61596. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  61597. return;
  61598. case 3:
  61599. if (this._defaultModel) {
  61600. if (notifyObject.pressed) {
  61601. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  61602. }
  61603. else {
  61604. (this._defaultModel.getChildren()[1]).position.y = 0;
  61605. }
  61606. }
  61607. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61608. return;
  61609. case 4:
  61610. if (this._defaultModel) {
  61611. if (notifyObject.pressed) {
  61612. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61613. }
  61614. else {
  61615. (this._defaultModel.getChildren()[2]).position.y = 0;
  61616. }
  61617. }
  61618. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61619. return;
  61620. case 5:
  61621. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  61622. return;
  61623. }
  61624. };
  61625. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  61626. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  61627. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  61628. return OculusTouchController;
  61629. }(BABYLON.WebVRController));
  61630. BABYLON.OculusTouchController = OculusTouchController;
  61631. })(BABYLON || (BABYLON = {}));
  61632. //# sourceMappingURL=babylon.oculusTouchController.js.map
  61633. var BABYLON;
  61634. (function (BABYLON) {
  61635. var ViveController = /** @class */ (function (_super) {
  61636. __extends(ViveController, _super);
  61637. function ViveController(vrGamepad) {
  61638. var _this = _super.call(this, vrGamepad) || this;
  61639. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  61640. _this._invertLeftStickY = true;
  61641. return _this;
  61642. }
  61643. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61644. var _this = this;
  61645. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  61646. /*
  61647. Parent Mesh name: ViveWand
  61648. - body
  61649. - r_gripper
  61650. - l_gripper
  61651. - menu_button
  61652. - system_button
  61653. - trackpad
  61654. - trigger
  61655. - LED
  61656. */
  61657. _this._defaultModel = newMeshes[1];
  61658. _this.attachToMesh(_this._defaultModel);
  61659. if (meshLoaded) {
  61660. meshLoaded(_this._defaultModel);
  61661. }
  61662. });
  61663. };
  61664. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  61665. get: function () {
  61666. return this.onMainButtonStateChangedObservable;
  61667. },
  61668. enumerable: true,
  61669. configurable: true
  61670. });
  61671. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  61672. get: function () {
  61673. return this.onMainButtonStateChangedObservable;
  61674. },
  61675. enumerable: true,
  61676. configurable: true
  61677. });
  61678. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  61679. get: function () {
  61680. return this.onSecondaryButtonStateChangedObservable;
  61681. },
  61682. enumerable: true,
  61683. configurable: true
  61684. });
  61685. /**
  61686. * Vive mapping:
  61687. * 0: touchpad
  61688. * 1: trigger
  61689. * 2: left AND right buttons
  61690. * 3: menu button
  61691. */
  61692. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61693. var notifyObject = state; //{ state: state, changes: changes };
  61694. switch (buttonIdx) {
  61695. case 0:
  61696. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61697. return;
  61698. case 1:// index trigger
  61699. if (this._defaultModel) {
  61700. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  61701. }
  61702. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61703. return;
  61704. case 2:// left AND right button
  61705. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61706. return;
  61707. case 3:
  61708. if (this._defaultModel) {
  61709. if (notifyObject.pressed) {
  61710. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61711. }
  61712. else {
  61713. (this._defaultModel.getChildren()[2]).position.y = 0;
  61714. }
  61715. }
  61716. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61717. return;
  61718. }
  61719. };
  61720. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  61721. ViveController.MODEL_FILENAME = 'wand.babylon';
  61722. return ViveController;
  61723. }(BABYLON.WebVRController));
  61724. BABYLON.ViveController = ViveController;
  61725. })(BABYLON || (BABYLON = {}));
  61726. //# sourceMappingURL=babylon.viveController.js.map
  61727. var BABYLON;
  61728. (function (BABYLON) {
  61729. var GenericController = /** @class */ (function (_super) {
  61730. __extends(GenericController, _super);
  61731. function GenericController(vrGamepad) {
  61732. return _super.call(this, vrGamepad) || this;
  61733. }
  61734. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61735. var _this = this;
  61736. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  61737. _this._defaultModel = newMeshes[1];
  61738. _this.attachToMesh(_this._defaultModel);
  61739. if (meshLoaded) {
  61740. meshLoaded(_this._defaultModel);
  61741. }
  61742. });
  61743. };
  61744. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61745. console.log("Button id: " + buttonIdx + "state: ");
  61746. console.dir(state);
  61747. };
  61748. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61749. GenericController.MODEL_FILENAME = 'generic.babylon';
  61750. return GenericController;
  61751. }(BABYLON.WebVRController));
  61752. BABYLON.GenericController = GenericController;
  61753. })(BABYLON || (BABYLON = {}));
  61754. //# sourceMappingURL=babylon.genericController.js.map
  61755. var BABYLON;
  61756. (function (BABYLON) {
  61757. var LoadedMeshInfo = /** @class */ (function () {
  61758. function LoadedMeshInfo() {
  61759. this.buttonMeshes = {};
  61760. this.axisMeshes = {};
  61761. }
  61762. return LoadedMeshInfo;
  61763. }());
  61764. var WindowsMotionController = /** @class */ (function (_super) {
  61765. __extends(WindowsMotionController, _super);
  61766. function WindowsMotionController(vrGamepad) {
  61767. var _this = _super.call(this, vrGamepad) || this;
  61768. _this._mapping = {
  61769. // Semantic button names
  61770. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  61771. // A mapping of the button name to glTF model node name
  61772. // that should be transformed by button value.
  61773. buttonMeshNames: {
  61774. 'trigger': 'SELECT',
  61775. 'menu': 'MENU',
  61776. 'grip': 'GRASP',
  61777. 'thumbstick': 'THUMBSTICK_PRESS',
  61778. 'trackpad': 'TOUCHPAD_PRESS'
  61779. },
  61780. // This mapping is used to translate from the Motion Controller to Babylon semantics
  61781. buttonObservableNames: {
  61782. 'trigger': 'onTriggerStateChangedObservable',
  61783. 'menu': 'onSecondaryButtonStateChangedObservable',
  61784. 'grip': 'onMainButtonStateChangedObservable',
  61785. 'thumbstick': 'onPadStateChangedObservable',
  61786. 'trackpad': 'onTrackpadChangedObservable'
  61787. },
  61788. // A mapping of the axis name to glTF model node name
  61789. // that should be transformed by axis value.
  61790. // This array mirrors the browserGamepad.axes array, such that
  61791. // the mesh corresponding to axis 0 is in this array index 0.
  61792. axisMeshNames: [
  61793. 'THUMBSTICK_X',
  61794. 'THUMBSTICK_Y',
  61795. 'TOUCHPAD_TOUCH_X',
  61796. 'TOUCHPAD_TOUCH_Y'
  61797. ],
  61798. pointingPoseMeshName: 'POINTING_POSE'
  61799. };
  61800. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  61801. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  61802. _this.trackpad = { x: 0, y: 0 };
  61803. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  61804. _this._loadedMeshInfo = null;
  61805. return _this;
  61806. }
  61807. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  61808. get: function () {
  61809. return this.onTriggerStateChangedObservable;
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  61815. get: function () {
  61816. return this.onSecondaryButtonStateChangedObservable;
  61817. },
  61818. enumerable: true,
  61819. configurable: true
  61820. });
  61821. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  61822. get: function () {
  61823. return this.onMainButtonStateChangedObservable;
  61824. },
  61825. enumerable: true,
  61826. configurable: true
  61827. });
  61828. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  61829. get: function () {
  61830. return this.onPadStateChangedObservable;
  61831. },
  61832. enumerable: true,
  61833. configurable: true
  61834. });
  61835. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  61836. get: function () {
  61837. return this.onTrackpadChangedObservable;
  61838. },
  61839. enumerable: true,
  61840. configurable: true
  61841. });
  61842. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  61843. get: function () {
  61844. return this.onTrackpadValuesChangedObservable;
  61845. },
  61846. enumerable: true,
  61847. configurable: true
  61848. });
  61849. /**
  61850. * Called once per frame by the engine.
  61851. */
  61852. WindowsMotionController.prototype.update = function () {
  61853. _super.prototype.update.call(this);
  61854. // Only need to animate axes if there is a loaded mesh
  61855. if (this._loadedMeshInfo) {
  61856. if (this.browserGamepad.axes) {
  61857. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  61858. this.trackpad.x = this.browserGamepad["axes"][2];
  61859. this.trackpad.y = this.browserGamepad["axes"][3];
  61860. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  61861. }
  61862. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  61863. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  61864. }
  61865. }
  61866. }
  61867. };
  61868. /**
  61869. * Called once for each button that changed state since the last frame
  61870. * @param buttonIdx Which button index changed
  61871. * @param state New state of the button
  61872. * @param changes Which properties on the state changed since last frame
  61873. */
  61874. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61875. var buttonName = this._mapping.buttons[buttonIdx];
  61876. if (!buttonName) {
  61877. return;
  61878. }
  61879. // Only emit events for buttons that we know how to map from index to name
  61880. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  61881. if (observable) {
  61882. observable.notifyObservers(state);
  61883. }
  61884. this.lerpButtonTransform(buttonName, state.value);
  61885. };
  61886. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  61887. // If there is no loaded mesh, there is nothing to transform.
  61888. if (!this._loadedMeshInfo) {
  61889. return;
  61890. }
  61891. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  61892. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61893. return;
  61894. }
  61895. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  61896. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  61897. };
  61898. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  61899. if (!this._loadedMeshInfo) {
  61900. return;
  61901. }
  61902. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  61903. if (!meshInfo) {
  61904. return;
  61905. }
  61906. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61907. return;
  61908. }
  61909. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  61910. var lerpValue = axisValue * 0.5 + 0.5;
  61911. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  61912. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  61913. };
  61914. /**
  61915. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  61916. * @param scene scene in which to add meshes
  61917. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  61918. */
  61919. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  61920. var _this = this;
  61921. if (forceDefault === void 0) { forceDefault = false; }
  61922. var path;
  61923. var filename;
  61924. // Checking if GLB loader is present
  61925. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  61926. // Determine the device specific folder based on the ID suffix
  61927. var device = 'default';
  61928. if (this.id && !forceDefault) {
  61929. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  61930. device = ((match && match[0]) || device);
  61931. }
  61932. // Hand
  61933. if (this.hand === 'left') {
  61934. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  61935. }
  61936. else {
  61937. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  61938. }
  61939. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  61940. }
  61941. else {
  61942. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  61943. path = BABYLON.GenericController.MODEL_BASE_URL;
  61944. filename = BABYLON.GenericController.MODEL_FILENAME;
  61945. }
  61946. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  61947. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  61948. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  61949. if (!_this._loadedMeshInfo) {
  61950. return;
  61951. }
  61952. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  61953. _this.attachToMesh(_this._defaultModel);
  61954. if (meshLoaded) {
  61955. meshLoaded(_this._defaultModel);
  61956. }
  61957. }, null, function (scene, message) {
  61958. BABYLON.Tools.Log(message);
  61959. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  61960. if (!forceDefault) {
  61961. _this.initControllerMesh(scene, meshLoaded, true);
  61962. }
  61963. });
  61964. };
  61965. /**
  61966. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  61967. * can be transformed by button presses and axes values, based on this._mapping.
  61968. *
  61969. * @param scene scene in which the meshes exist
  61970. * @param meshes list of meshes that make up the controller model to process
  61971. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  61972. */
  61973. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  61974. var loadedMeshInfo = null;
  61975. // Create a new mesh to contain the glTF hierarchy
  61976. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  61977. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  61978. var childMesh = null;
  61979. for (var i = 0; i < meshes.length; i++) {
  61980. var mesh = meshes[i];
  61981. if (!mesh.parent) {
  61982. // Exclude controller meshes from picking results
  61983. mesh.isPickable = false;
  61984. // Handle root node, attach to the new parentMesh
  61985. childMesh = mesh;
  61986. break;
  61987. }
  61988. }
  61989. if (childMesh) {
  61990. childMesh.setParent(parentMesh);
  61991. // Create our mesh info. Note that this method will always return non-null.
  61992. loadedMeshInfo = this.createMeshInfo(parentMesh);
  61993. }
  61994. else {
  61995. BABYLON.Tools.Warn('Could not find root node in model file.');
  61996. }
  61997. return loadedMeshInfo;
  61998. };
  61999. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  62000. var loadedMeshInfo = new LoadedMeshInfo();
  62001. var i;
  62002. loadedMeshInfo.rootNode = rootNode;
  62003. // Reset the caches
  62004. loadedMeshInfo.buttonMeshes = {};
  62005. loadedMeshInfo.axisMeshes = {};
  62006. // Button Meshes
  62007. for (i = 0; i < this._mapping.buttons.length; i++) {
  62008. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  62009. if (!buttonMeshName) {
  62010. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  62011. continue;
  62012. }
  62013. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  62014. if (!buttonMesh) {
  62015. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  62016. continue;
  62017. }
  62018. var buttonMeshInfo = {
  62019. index: i,
  62020. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  62021. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  62022. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  62023. };
  62024. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  62025. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  62026. }
  62027. else {
  62028. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  62029. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  62030. '(VALUE: ' + !!buttonMeshInfo.value +
  62031. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  62032. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  62033. ')');
  62034. }
  62035. }
  62036. // Axis Meshes
  62037. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  62038. var axisMeshName = this._mapping.axisMeshNames[i];
  62039. if (!axisMeshName) {
  62040. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  62041. continue;
  62042. }
  62043. var axisMesh = getChildByName(rootNode, axisMeshName);
  62044. if (!axisMesh) {
  62045. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  62046. continue;
  62047. }
  62048. var axisMeshInfo = {
  62049. index: i,
  62050. value: getImmediateChildByName(axisMesh, 'VALUE'),
  62051. min: getImmediateChildByName(axisMesh, 'MIN'),
  62052. max: getImmediateChildByName(axisMesh, 'MAX')
  62053. };
  62054. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  62055. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  62056. }
  62057. else {
  62058. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  62059. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  62060. '(VALUE: ' + !!axisMeshInfo.value +
  62061. ', MIN: ' + !!axisMeshInfo.min +
  62062. ', MAX:' + !!axisMeshInfo.max +
  62063. ')');
  62064. }
  62065. }
  62066. // Pointing Ray
  62067. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  62068. if (!loadedMeshInfo.pointingPoseNode) {
  62069. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  62070. }
  62071. return loadedMeshInfo;
  62072. // Look through all children recursively. This will return null if no mesh exists with the given name.
  62073. function getChildByName(node, name) {
  62074. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  62075. }
  62076. // Look through only immediate children. This will return null if no mesh exists with the given name.
  62077. function getImmediateChildByName(node, name) {
  62078. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  62079. }
  62080. };
  62081. WindowsMotionController.prototype.getForwardRay = function (length) {
  62082. if (length === void 0) { length = 100; }
  62083. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  62084. return _super.prototype.getForwardRay.call(this, length);
  62085. }
  62086. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  62087. var origin = m.getTranslation();
  62088. var forward = new BABYLON.Vector3(0, 0, -1);
  62089. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  62090. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  62091. return new BABYLON.Ray(origin, direction, length);
  62092. };
  62093. WindowsMotionController.prototype.dispose = function () {
  62094. _super.prototype.dispose.call(this);
  62095. this.onTrackpadChangedObservable.clear();
  62096. };
  62097. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  62098. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  62099. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  62100. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  62101. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  62102. return WindowsMotionController;
  62103. }(BABYLON.WebVRController));
  62104. BABYLON.WindowsMotionController = WindowsMotionController;
  62105. })(BABYLON || (BABYLON = {}));
  62106. //# sourceMappingURL=babylon.windowsMotionController.js.map
  62107. var BABYLON;
  62108. (function (BABYLON) {
  62109. var GearVRController = /** @class */ (function (_super) {
  62110. __extends(GearVRController, _super);
  62111. function GearVRController(vrGamepad) {
  62112. var _this = _super.call(this, vrGamepad) || this;
  62113. _this._buttonIndexToObservableNameMap = [
  62114. 'onTrackpadChangedObservable',
  62115. 'onTriggerStateChangedObservable' // Trigger
  62116. ];
  62117. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  62118. return _this;
  62119. }
  62120. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62121. var _this = this;
  62122. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  62123. _this._defaultModel = newMeshes[1];
  62124. _this.attachToMesh(_this._defaultModel);
  62125. if (meshLoaded) {
  62126. meshLoaded(_this._defaultModel);
  62127. }
  62128. });
  62129. };
  62130. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62131. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  62132. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  62133. // Only emit events for buttons that we know how to map from index to observable
  62134. var observable = this[observableName];
  62135. if (observable) {
  62136. observable.notifyObservers(state);
  62137. }
  62138. }
  62139. };
  62140. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  62141. GearVRController.MODEL_FILENAME = 'generic.babylon';
  62142. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  62143. return GearVRController;
  62144. }(BABYLON.WebVRController));
  62145. BABYLON.GearVRController = GearVRController;
  62146. })(BABYLON || (BABYLON = {}));
  62147. //# sourceMappingURL=babylon.gearVRController.js.map
  62148. var BABYLON;
  62149. (function (BABYLON) {
  62150. var FollowCamera = /** @class */ (function (_super) {
  62151. __extends(FollowCamera, _super);
  62152. function FollowCamera(name, position, scene, lockedTarget) {
  62153. if (lockedTarget === void 0) { lockedTarget = null; }
  62154. var _this = _super.call(this, name, position, scene) || this;
  62155. _this.radius = 12;
  62156. _this.rotationOffset = 0;
  62157. _this.heightOffset = 4;
  62158. _this.cameraAcceleration = 0.05;
  62159. _this.maxCameraSpeed = 20;
  62160. _this.lockedTarget = lockedTarget;
  62161. return _this;
  62162. }
  62163. FollowCamera.prototype.getRadians = function (degrees) {
  62164. return degrees * Math.PI / 180;
  62165. };
  62166. FollowCamera.prototype.follow = function (cameraTarget) {
  62167. if (!cameraTarget)
  62168. return;
  62169. var yRotation;
  62170. if (cameraTarget.rotationQuaternion) {
  62171. var rotMatrix = new BABYLON.Matrix();
  62172. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  62173. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  62174. }
  62175. else {
  62176. yRotation = cameraTarget.rotation.y;
  62177. }
  62178. var radians = this.getRadians(this.rotationOffset) + yRotation;
  62179. var targetPosition = cameraTarget.getAbsolutePosition();
  62180. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  62181. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  62182. var dx = targetX - this.position.x;
  62183. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  62184. var dz = (targetZ) - this.position.z;
  62185. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  62186. var vy = dy * this.cameraAcceleration;
  62187. var vz = dz * this.cameraAcceleration * 2;
  62188. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  62189. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62190. }
  62191. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  62192. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62193. }
  62194. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  62195. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62196. }
  62197. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  62198. this.setTarget(targetPosition);
  62199. };
  62200. FollowCamera.prototype._checkInputs = function () {
  62201. _super.prototype._checkInputs.call(this);
  62202. if (this.lockedTarget) {
  62203. this.follow(this.lockedTarget);
  62204. }
  62205. };
  62206. FollowCamera.prototype.getClassName = function () {
  62207. return "FollowCamera";
  62208. };
  62209. __decorate([
  62210. BABYLON.serialize()
  62211. ], FollowCamera.prototype, "radius", void 0);
  62212. __decorate([
  62213. BABYLON.serialize()
  62214. ], FollowCamera.prototype, "rotationOffset", void 0);
  62215. __decorate([
  62216. BABYLON.serialize()
  62217. ], FollowCamera.prototype, "heightOffset", void 0);
  62218. __decorate([
  62219. BABYLON.serialize()
  62220. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  62221. __decorate([
  62222. BABYLON.serialize()
  62223. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  62224. __decorate([
  62225. BABYLON.serializeAsMeshReference("lockedTargetId")
  62226. ], FollowCamera.prototype, "lockedTarget", void 0);
  62227. return FollowCamera;
  62228. }(BABYLON.TargetCamera));
  62229. BABYLON.FollowCamera = FollowCamera;
  62230. var ArcFollowCamera = /** @class */ (function (_super) {
  62231. __extends(ArcFollowCamera, _super);
  62232. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  62233. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  62234. _this.alpha = alpha;
  62235. _this.beta = beta;
  62236. _this.radius = radius;
  62237. _this.target = target;
  62238. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  62239. _this.follow();
  62240. return _this;
  62241. }
  62242. ArcFollowCamera.prototype.follow = function () {
  62243. if (!this.target) {
  62244. return;
  62245. }
  62246. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  62247. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  62248. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  62249. var targetPosition = this.target.getAbsolutePosition();
  62250. this.position = targetPosition.add(this._cartesianCoordinates);
  62251. this.setTarget(targetPosition);
  62252. };
  62253. ArcFollowCamera.prototype._checkInputs = function () {
  62254. _super.prototype._checkInputs.call(this);
  62255. this.follow();
  62256. };
  62257. ArcFollowCamera.prototype.getClassName = function () {
  62258. return "ArcFollowCamera";
  62259. };
  62260. return ArcFollowCamera;
  62261. }(BABYLON.TargetCamera));
  62262. BABYLON.ArcFollowCamera = ArcFollowCamera;
  62263. })(BABYLON || (BABYLON = {}));
  62264. //# sourceMappingURL=babylon.followCamera.js.map
  62265. var BABYLON;
  62266. (function (BABYLON) {
  62267. // We're mainly based on the logic defined into the FreeCamera code
  62268. var UniversalCamera = /** @class */ (function (_super) {
  62269. __extends(UniversalCamera, _super);
  62270. //-- end properties for backward compatibility for inputs
  62271. function UniversalCamera(name, position, scene) {
  62272. var _this = _super.call(this, name, position, scene) || this;
  62273. _this.inputs.addGamepad();
  62274. return _this;
  62275. }
  62276. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  62277. //-- Begin properties for backward compatibility for inputs
  62278. get: function () {
  62279. var gamepad = this.inputs.attached["gamepad"];
  62280. if (gamepad)
  62281. return gamepad.gamepadAngularSensibility;
  62282. return 0;
  62283. },
  62284. set: function (value) {
  62285. var gamepad = this.inputs.attached["gamepad"];
  62286. if (gamepad)
  62287. gamepad.gamepadAngularSensibility = value;
  62288. },
  62289. enumerable: true,
  62290. configurable: true
  62291. });
  62292. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  62293. get: function () {
  62294. var gamepad = this.inputs.attached["gamepad"];
  62295. if (gamepad)
  62296. return gamepad.gamepadMoveSensibility;
  62297. return 0;
  62298. },
  62299. set: function (value) {
  62300. var gamepad = this.inputs.attached["gamepad"];
  62301. if (gamepad)
  62302. gamepad.gamepadMoveSensibility = value;
  62303. },
  62304. enumerable: true,
  62305. configurable: true
  62306. });
  62307. UniversalCamera.prototype.getClassName = function () {
  62308. return "UniversalCamera";
  62309. };
  62310. return UniversalCamera;
  62311. }(BABYLON.TouchCamera));
  62312. BABYLON.UniversalCamera = UniversalCamera;
  62313. })(BABYLON || (BABYLON = {}));
  62314. //# sourceMappingURL=babylon.universalCamera.js.map
  62315. var BABYLON;
  62316. (function (BABYLON) {
  62317. // We're mainly based on the logic defined into the FreeCamera code
  62318. var GamepadCamera = /** @class */ (function (_super) {
  62319. __extends(GamepadCamera, _super);
  62320. //-- end properties for backward compatibility for inputs
  62321. function GamepadCamera(name, position, scene) {
  62322. return _super.call(this, name, position, scene) || this;
  62323. }
  62324. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  62325. //-- Begin properties for backward compatibility for inputs
  62326. get: function () {
  62327. var gamepad = this.inputs.attached["gamepad"];
  62328. if (gamepad)
  62329. return gamepad.gamepadAngularSensibility;
  62330. return 0;
  62331. },
  62332. set: function (value) {
  62333. var gamepad = this.inputs.attached["gamepad"];
  62334. if (gamepad)
  62335. gamepad.gamepadAngularSensibility = value;
  62336. },
  62337. enumerable: true,
  62338. configurable: true
  62339. });
  62340. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  62341. get: function () {
  62342. var gamepad = this.inputs.attached["gamepad"];
  62343. if (gamepad)
  62344. return gamepad.gamepadMoveSensibility;
  62345. return 0;
  62346. },
  62347. set: function (value) {
  62348. var gamepad = this.inputs.attached["gamepad"];
  62349. if (gamepad)
  62350. gamepad.gamepadMoveSensibility = value;
  62351. },
  62352. enumerable: true,
  62353. configurable: true
  62354. });
  62355. GamepadCamera.prototype.getClassName = function () {
  62356. return "GamepadCamera";
  62357. };
  62358. return GamepadCamera;
  62359. }(BABYLON.UniversalCamera));
  62360. BABYLON.GamepadCamera = GamepadCamera;
  62361. })(BABYLON || (BABYLON = {}));
  62362. //# sourceMappingURL=babylon.gamepadCamera.js.map
  62363. var BABYLON;
  62364. (function (BABYLON) {
  62365. var PostProcessRenderPipelineManager = /** @class */ (function () {
  62366. function PostProcessRenderPipelineManager() {
  62367. this._renderPipelines = {};
  62368. }
  62369. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  62370. this._renderPipelines[renderPipeline._name] = renderPipeline;
  62371. };
  62372. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  62373. if (unique === void 0) { unique = false; }
  62374. var renderPipeline = this._renderPipelines[renderPipelineName];
  62375. if (!renderPipeline) {
  62376. return;
  62377. }
  62378. renderPipeline._attachCameras(cameras, unique);
  62379. };
  62380. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  62381. var renderPipeline = this._renderPipelines[renderPipelineName];
  62382. if (!renderPipeline) {
  62383. return;
  62384. }
  62385. renderPipeline._detachCameras(cameras);
  62386. };
  62387. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62388. var renderPipeline = this._renderPipelines[renderPipelineName];
  62389. if (!renderPipeline) {
  62390. return;
  62391. }
  62392. renderPipeline._enableEffect(renderEffectName, cameras);
  62393. };
  62394. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62395. var renderPipeline = this._renderPipelines[renderPipelineName];
  62396. if (!renderPipeline) {
  62397. return;
  62398. }
  62399. renderPipeline._disableEffect(renderEffectName, cameras);
  62400. };
  62401. PostProcessRenderPipelineManager.prototype.update = function () {
  62402. for (var renderPipelineName in this._renderPipelines) {
  62403. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62404. var pipeline = this._renderPipelines[renderPipelineName];
  62405. if (!pipeline.isSupported) {
  62406. pipeline.dispose();
  62407. delete this._renderPipelines[renderPipelineName];
  62408. }
  62409. else {
  62410. pipeline._update();
  62411. }
  62412. }
  62413. }
  62414. };
  62415. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  62416. for (var renderPipelineName in this._renderPipelines) {
  62417. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62418. var pipeline = this._renderPipelines[renderPipelineName];
  62419. pipeline._rebuild();
  62420. }
  62421. }
  62422. };
  62423. PostProcessRenderPipelineManager.prototype.dispose = function () {
  62424. for (var renderPipelineName in this._renderPipelines) {
  62425. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62426. var pipeline = this._renderPipelines[renderPipelineName];
  62427. pipeline.dispose();
  62428. }
  62429. }
  62430. };
  62431. return PostProcessRenderPipelineManager;
  62432. }());
  62433. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  62434. })(BABYLON || (BABYLON = {}));
  62435. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  62436. var BABYLON;
  62437. (function (BABYLON) {
  62438. /**
  62439. * This represents a set of one or more post processes in Babylon.
  62440. * A post process can be used to apply a shader to a texture after it is rendered.
  62441. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  62442. */
  62443. var PostProcessRenderEffect = /** @class */ (function () {
  62444. /**
  62445. * Instantiates a post process render effect.
  62446. * A post process can be used to apply a shader to a texture after it is rendered.
  62447. * @param engine The engine the effect is tied to
  62448. * @param name The name of the effect
  62449. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  62450. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  62451. */
  62452. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  62453. this._name = name;
  62454. this._singleInstance = singleInstance || true;
  62455. this._getPostProcesses = getPostProcesses;
  62456. this._cameras = {};
  62457. this._indicesForCamera = {};
  62458. this._postProcesses = {};
  62459. }
  62460. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  62461. /**
  62462. * Checks if all the post processes in the effect are supported.
  62463. */
  62464. get: function () {
  62465. for (var index in this._postProcesses) {
  62466. for (var ppIndex in this._postProcesses[index]) {
  62467. if (!this._postProcesses[index][ppIndex].isSupported) {
  62468. return false;
  62469. }
  62470. }
  62471. }
  62472. return true;
  62473. },
  62474. enumerable: true,
  62475. configurable: true
  62476. });
  62477. /**
  62478. * Updates the current state of the effect
  62479. */
  62480. PostProcessRenderEffect.prototype._update = function () {
  62481. };
  62482. /**
  62483. * Attaches the effect on cameras
  62484. * @param cameras The camera to attach to.
  62485. */
  62486. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  62487. var _this = this;
  62488. var cameraKey;
  62489. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62490. if (!cams) {
  62491. return;
  62492. }
  62493. for (var i = 0; i < cams.length; i++) {
  62494. var camera = cams[i];
  62495. var cameraName = camera.name;
  62496. if (this._singleInstance) {
  62497. cameraKey = 0;
  62498. }
  62499. else {
  62500. cameraKey = cameraName;
  62501. }
  62502. if (!this._postProcesses[cameraKey]) {
  62503. var postProcess = this._getPostProcesses();
  62504. if (postProcess) {
  62505. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  62506. }
  62507. }
  62508. if (!this._indicesForCamera[cameraName]) {
  62509. this._indicesForCamera[cameraName] = [];
  62510. }
  62511. this._postProcesses[cameraKey].forEach(function (postProcess) {
  62512. var index = camera.attachPostProcess(postProcess);
  62513. _this._indicesForCamera[cameraName].push(index);
  62514. });
  62515. if (!this._cameras[cameraName]) {
  62516. this._cameras[cameraName] = camera;
  62517. }
  62518. }
  62519. };
  62520. /**
  62521. * Detatches the effect on cameras
  62522. * @param cameras The camera to detatch from.
  62523. */
  62524. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  62525. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62526. if (!cams) {
  62527. return;
  62528. }
  62529. for (var i = 0; i < cams.length; i++) {
  62530. var camera = cams[i];
  62531. var cameraName = camera.name;
  62532. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  62533. camera.detachPostProcess(postProcess);
  62534. });
  62535. if (this._cameras[cameraName]) {
  62536. //this._indicesForCamera.splice(index, 1);
  62537. this._cameras[cameraName] = null;
  62538. }
  62539. }
  62540. };
  62541. /**
  62542. * Enables the effect on given cameras
  62543. * @param cameras The camera to enable.
  62544. */
  62545. PostProcessRenderEffect.prototype._enable = function (cameras) {
  62546. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62547. if (!cams) {
  62548. return;
  62549. }
  62550. for (var i = 0; i < cams.length; i++) {
  62551. var camera = cams[i];
  62552. var cameraName = camera.name;
  62553. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  62554. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  62555. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  62556. }
  62557. }
  62558. }
  62559. };
  62560. /**
  62561. * Disables the effect on the given cameras
  62562. * @param cameras The camera to disable.
  62563. */
  62564. PostProcessRenderEffect.prototype._disable = function (cameras) {
  62565. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62566. if (!cams) {
  62567. return;
  62568. }
  62569. for (var i = 0; i < cams.length; i++) {
  62570. var camera = cams[i];
  62571. var cameraName = camera.Name;
  62572. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  62573. }
  62574. };
  62575. /**
  62576. * Gets a list of the post processes contained in the effect.
  62577. * @param camera The camera to get the post processes on.
  62578. * @returns The list of the post processes in the effect.
  62579. */
  62580. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  62581. if (this._singleInstance) {
  62582. return this._postProcesses[0];
  62583. }
  62584. else {
  62585. if (!camera) {
  62586. return null;
  62587. }
  62588. return this._postProcesses[camera.name];
  62589. }
  62590. };
  62591. return PostProcessRenderEffect;
  62592. }());
  62593. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  62594. })(BABYLON || (BABYLON = {}));
  62595. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  62596. var BABYLON;
  62597. (function (BABYLON) {
  62598. var PostProcessRenderPipeline = /** @class */ (function () {
  62599. function PostProcessRenderPipeline(engine, name) {
  62600. this._name = name;
  62601. this._renderEffects = {};
  62602. this._renderEffectsForIsolatedPass = new Array();
  62603. this._cameras = [];
  62604. }
  62605. PostProcessRenderPipeline.prototype.getClassName = function () {
  62606. return "PostProcessRenderPipeline";
  62607. };
  62608. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  62609. get: function () {
  62610. for (var renderEffectName in this._renderEffects) {
  62611. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62612. if (!this._renderEffects[renderEffectName].isSupported) {
  62613. return false;
  62614. }
  62615. }
  62616. }
  62617. return true;
  62618. },
  62619. enumerable: true,
  62620. configurable: true
  62621. });
  62622. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  62623. this._renderEffects[renderEffect._name] = renderEffect;
  62624. };
  62625. // private
  62626. PostProcessRenderPipeline.prototype._rebuild = function () {
  62627. };
  62628. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62629. var renderEffects = this._renderEffects[renderEffectName];
  62630. if (!renderEffects) {
  62631. return;
  62632. }
  62633. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62634. };
  62635. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  62636. var renderEffects = this._renderEffects[renderEffectName];
  62637. if (!renderEffects) {
  62638. return;
  62639. }
  62640. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62641. };
  62642. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  62643. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62644. if (!cams) {
  62645. return;
  62646. }
  62647. var indicesToDelete = [];
  62648. var i;
  62649. for (i = 0; i < cams.length; i++) {
  62650. var camera = cams[i];
  62651. var cameraName = camera.name;
  62652. if (this._cameras.indexOf(camera) === -1) {
  62653. this._cameras[cameraName] = camera;
  62654. }
  62655. else if (unique) {
  62656. indicesToDelete.push(i);
  62657. }
  62658. }
  62659. for (i = 0; i < indicesToDelete.length; i++) {
  62660. cameras.splice(indicesToDelete[i], 1);
  62661. }
  62662. for (var renderEffectName in this._renderEffects) {
  62663. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62664. this._renderEffects[renderEffectName]._attachCameras(cams);
  62665. }
  62666. }
  62667. };
  62668. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  62669. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62670. if (!cams) {
  62671. return;
  62672. }
  62673. for (var renderEffectName in this._renderEffects) {
  62674. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62675. this._renderEffects[renderEffectName]._detachCameras(cams);
  62676. }
  62677. }
  62678. for (var i = 0; i < cams.length; i++) {
  62679. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  62680. }
  62681. };
  62682. PostProcessRenderPipeline.prototype._update = function () {
  62683. for (var renderEffectName in this._renderEffects) {
  62684. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62685. this._renderEffects[renderEffectName]._update();
  62686. }
  62687. }
  62688. for (var i = 0; i < this._cameras.length; i++) {
  62689. var cameraName = this._cameras[i].name;
  62690. if (this._renderEffectsForIsolatedPass[cameraName]) {
  62691. this._renderEffectsForIsolatedPass[cameraName]._update();
  62692. }
  62693. }
  62694. };
  62695. PostProcessRenderPipeline.prototype._reset = function () {
  62696. this._renderEffects = {};
  62697. this._renderEffectsForIsolatedPass = new Array();
  62698. };
  62699. PostProcessRenderPipeline.prototype.dispose = function () {
  62700. // Must be implemented by children
  62701. };
  62702. __decorate([
  62703. BABYLON.serialize()
  62704. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  62705. return PostProcessRenderPipeline;
  62706. }());
  62707. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  62708. })(BABYLON || (BABYLON = {}));
  62709. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  62710. var BABYLON;
  62711. (function (BABYLON) {
  62712. var DepthRenderer = /** @class */ (function () {
  62713. function DepthRenderer(scene, type) {
  62714. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  62715. var _this = this;
  62716. this._scene = scene;
  62717. var engine = scene.getEngine();
  62718. // Render target
  62719. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  62720. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62721. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62722. this._depthMap.refreshRate = 1;
  62723. this._depthMap.renderParticles = false;
  62724. this._depthMap.renderList = null;
  62725. // set default depth value to 1.0 (far away)
  62726. this._depthMap.onClearObservable.add(function (engine) {
  62727. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  62728. });
  62729. // Custom render function
  62730. var renderSubMesh = function (subMesh) {
  62731. var mesh = subMesh.getRenderingMesh();
  62732. var scene = _this._scene;
  62733. var engine = scene.getEngine();
  62734. var material = subMesh.getMaterial();
  62735. if (!material) {
  62736. return;
  62737. }
  62738. // Culling and reverse (right handed system)
  62739. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62740. // Managing instances
  62741. var batch = mesh._getInstancesRenderList(subMesh._id);
  62742. if (batch.mustReturn) {
  62743. return;
  62744. }
  62745. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62746. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  62747. engine.enableEffect(_this._effect);
  62748. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62749. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62750. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  62751. // Alpha test
  62752. if (material && material.needAlphaTesting()) {
  62753. var alphaTexture = material.getAlphaTestTexture();
  62754. if (alphaTexture) {
  62755. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62756. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62757. }
  62758. }
  62759. // Bones
  62760. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62761. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62762. }
  62763. // Draw
  62764. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62765. }
  62766. };
  62767. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62768. var index;
  62769. if (depthOnlySubMeshes.length) {
  62770. engine.setColorWrite(false);
  62771. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62772. renderSubMesh(depthOnlySubMeshes.data[index]);
  62773. }
  62774. engine.setColorWrite(true);
  62775. }
  62776. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62777. renderSubMesh(opaqueSubMeshes.data[index]);
  62778. }
  62779. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62780. renderSubMesh(alphaTestSubMeshes.data[index]);
  62781. }
  62782. };
  62783. }
  62784. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62785. var material = subMesh.getMaterial();
  62786. if (material.disableDepthWrite) {
  62787. return false;
  62788. }
  62789. var defines = [];
  62790. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62791. var mesh = subMesh.getMesh();
  62792. // Alpha test
  62793. if (material && material.needAlphaTesting()) {
  62794. defines.push("#define ALPHATEST");
  62795. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62796. attribs.push(BABYLON.VertexBuffer.UVKind);
  62797. defines.push("#define UV1");
  62798. }
  62799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62800. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62801. defines.push("#define UV2");
  62802. }
  62803. }
  62804. // Bones
  62805. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62806. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62807. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62808. if (mesh.numBoneInfluencers > 4) {
  62809. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62810. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62811. }
  62812. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62813. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62814. }
  62815. else {
  62816. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62817. }
  62818. // Instances
  62819. if (useInstances) {
  62820. defines.push("#define INSTANCES");
  62821. attribs.push("world0");
  62822. attribs.push("world1");
  62823. attribs.push("world2");
  62824. attribs.push("world3");
  62825. }
  62826. // Get correct effect
  62827. var join = defines.join("\n");
  62828. if (this._cachedDefines !== join) {
  62829. this._cachedDefines = join;
  62830. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62831. }
  62832. return this._effect.isReady();
  62833. };
  62834. DepthRenderer.prototype.getDepthMap = function () {
  62835. return this._depthMap;
  62836. };
  62837. // Methods
  62838. DepthRenderer.prototype.dispose = function () {
  62839. this._depthMap.dispose();
  62840. };
  62841. return DepthRenderer;
  62842. }());
  62843. BABYLON.DepthRenderer = DepthRenderer;
  62844. })(BABYLON || (BABYLON = {}));
  62845. //# sourceMappingURL=babylon.depthRenderer.js.map
  62846. var BABYLON;
  62847. (function (BABYLON) {
  62848. var SSAORenderingPipeline = /** @class */ (function (_super) {
  62849. __extends(SSAORenderingPipeline, _super);
  62850. /**
  62851. * @constructor
  62852. * @param {string} name - The rendering pipeline name
  62853. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62854. * @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 }
  62855. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62856. */
  62857. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  62858. var _this = _super.call(this, scene.getEngine(), name) || this;
  62859. // Members
  62860. /**
  62861. * The PassPostProcess id in the pipeline that contains the original scene color
  62862. * @type {string}
  62863. */
  62864. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62865. /**
  62866. * The SSAO PostProcess id in the pipeline
  62867. * @type {string}
  62868. */
  62869. _this.SSAORenderEffect = "SSAORenderEffect";
  62870. /**
  62871. * The horizontal blur PostProcess id in the pipeline
  62872. * @type {string}
  62873. */
  62874. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62875. /**
  62876. * The vertical blur PostProcess id in the pipeline
  62877. * @type {string}
  62878. */
  62879. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62880. /**
  62881. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62882. * @type {string}
  62883. */
  62884. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62885. /**
  62886. * The output strength of the SSAO post-process. Default value is 1.0.
  62887. * @type {number}
  62888. */
  62889. _this.totalStrength = 1.0;
  62890. /**
  62891. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  62892. * @type {number}
  62893. */
  62894. _this.radius = 0.0001;
  62895. /**
  62896. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  62897. * Must not be equal to fallOff and superior to fallOff.
  62898. * Default value is 0.975
  62899. * @type {number}
  62900. */
  62901. _this.area = 0.0075;
  62902. /**
  62903. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  62904. * Must not be equal to area and inferior to area.
  62905. * Default value is 0.0
  62906. * @type {number}
  62907. */
  62908. _this.fallOff = 0.000001;
  62909. /**
  62910. * The base color of the SSAO post-process
  62911. * The final result is "base + ssao" between [0, 1]
  62912. * @type {number}
  62913. */
  62914. _this.base = 0.5;
  62915. _this._firstUpdate = true;
  62916. _this._scene = scene;
  62917. // Set up assets
  62918. _this._createRandomTexture();
  62919. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62920. var ssaoRatio = ratio.ssaoRatio || ratio;
  62921. var combineRatio = ratio.combineRatio || ratio;
  62922. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62923. _this._createSSAOPostProcess(ssaoRatio);
  62924. _this._createBlurPostProcess(ssaoRatio);
  62925. _this._createSSAOCombinePostProcess(combineRatio);
  62926. // Set up pipeline
  62927. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62928. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62929. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62930. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62931. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62932. // Finish
  62933. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62934. if (cameras)
  62935. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62936. return _this;
  62937. }
  62938. // Public Methods
  62939. /**
  62940. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62941. */
  62942. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62943. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62944. for (var i = 0; i < this._scene.cameras.length; i++) {
  62945. var camera = this._scene.cameras[i];
  62946. this._originalColorPostProcess.dispose(camera);
  62947. this._ssaoPostProcess.dispose(camera);
  62948. this._blurHPostProcess.dispose(camera);
  62949. this._blurVPostProcess.dispose(camera);
  62950. this._ssaoCombinePostProcess.dispose(camera);
  62951. }
  62952. this._randomTexture.dispose();
  62953. if (disableDepthRender)
  62954. this._scene.disableDepthRenderer();
  62955. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62956. _super.prototype.dispose.call(this);
  62957. };
  62958. // Private Methods
  62959. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62960. var _this = this;
  62961. var size = 16;
  62962. 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);
  62963. 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);
  62964. this._blurHPostProcess.onActivateObservable.add(function () {
  62965. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62966. _this._blurHPostProcess.kernel = size * dw;
  62967. });
  62968. this._blurVPostProcess.onActivateObservable.add(function () {
  62969. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62970. _this._blurVPostProcess.kernel = size * dw;
  62971. });
  62972. };
  62973. SSAORenderingPipeline.prototype._rebuild = function () {
  62974. this._firstUpdate = true;
  62975. _super.prototype._rebuild.call(this);
  62976. };
  62977. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62978. var _this = this;
  62979. var numSamples = 16;
  62980. var sampleSphere = [
  62981. 0.5381, 0.1856, -0.4319,
  62982. 0.1379, 0.2486, 0.4430,
  62983. 0.3371, 0.5679, -0.0057,
  62984. -0.6999, -0.0451, -0.0019,
  62985. 0.0689, -0.1598, -0.8547,
  62986. 0.0560, 0.0069, -0.1843,
  62987. -0.0146, 0.1402, 0.0762,
  62988. 0.0100, -0.1924, -0.0344,
  62989. -0.3577, -0.5301, -0.4358,
  62990. -0.3169, 0.1063, 0.0158,
  62991. 0.0103, -0.5869, 0.0046,
  62992. -0.0897, -0.4940, 0.3287,
  62993. 0.7119, -0.0154, -0.0918,
  62994. -0.0533, 0.0596, -0.5411,
  62995. 0.0352, -0.0631, 0.5460,
  62996. -0.4776, 0.2847, -0.0271
  62997. ];
  62998. var samplesFactor = 1.0 / numSamples;
  62999. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  63000. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63001. "area", "fallOff", "base", "range", "viewport"
  63002. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63003. this._ssaoPostProcess.onApply = function (effect) {
  63004. if (_this._firstUpdate) {
  63005. effect.setArray3("sampleSphere", sampleSphere);
  63006. effect.setFloat("samplesFactor", samplesFactor);
  63007. effect.setFloat("randTextureTiles", 4.0);
  63008. }
  63009. effect.setFloat("totalStrength", _this.totalStrength);
  63010. effect.setFloat("radius", _this.radius);
  63011. effect.setFloat("area", _this.area);
  63012. effect.setFloat("fallOff", _this.fallOff);
  63013. effect.setFloat("base", _this.base);
  63014. effect.setTexture("textureSampler", _this._depthTexture);
  63015. effect.setTexture("randomSampler", _this._randomTexture);
  63016. };
  63017. };
  63018. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63019. var _this = this;
  63020. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63021. this._ssaoCombinePostProcess.onApply = function (effect) {
  63022. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63023. };
  63024. };
  63025. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  63026. var size = 512;
  63027. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63028. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63029. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63030. var context = this._randomTexture.getContext();
  63031. var rand = function (min, max) {
  63032. return Math.random() * (max - min) + min;
  63033. };
  63034. var randVector = BABYLON.Vector3.Zero();
  63035. for (var x = 0; x < size; x++) {
  63036. for (var y = 0; y < size; y++) {
  63037. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  63038. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  63039. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  63040. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63041. context.fillRect(x, y, 1, 1);
  63042. }
  63043. }
  63044. this._randomTexture.update(false);
  63045. };
  63046. __decorate([
  63047. BABYLON.serialize()
  63048. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  63049. __decorate([
  63050. BABYLON.serialize()
  63051. ], SSAORenderingPipeline.prototype, "radius", void 0);
  63052. __decorate([
  63053. BABYLON.serialize()
  63054. ], SSAORenderingPipeline.prototype, "area", void 0);
  63055. __decorate([
  63056. BABYLON.serialize()
  63057. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  63058. __decorate([
  63059. BABYLON.serialize()
  63060. ], SSAORenderingPipeline.prototype, "base", void 0);
  63061. return SSAORenderingPipeline;
  63062. }(BABYLON.PostProcessRenderPipeline));
  63063. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  63064. })(BABYLON || (BABYLON = {}));
  63065. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  63066. var BABYLON;
  63067. (function (BABYLON) {
  63068. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  63069. __extends(SSAO2RenderingPipeline, _super);
  63070. /**
  63071. * @constructor
  63072. * @param {string} name - The rendering pipeline name
  63073. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63074. * @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 }
  63075. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63076. */
  63077. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  63078. var _this = _super.call(this, scene.getEngine(), name) || this;
  63079. // Members
  63080. /**
  63081. * The PassPostProcess id in the pipeline that contains the original scene color
  63082. * @type {string}
  63083. */
  63084. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  63085. /**
  63086. * The SSAO PostProcess id in the pipeline
  63087. * @type {string}
  63088. */
  63089. _this.SSAORenderEffect = "SSAORenderEffect";
  63090. /**
  63091. * The horizontal blur PostProcess id in the pipeline
  63092. * @type {string}
  63093. */
  63094. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  63095. /**
  63096. * The vertical blur PostProcess id in the pipeline
  63097. * @type {string}
  63098. */
  63099. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  63100. /**
  63101. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  63102. * @type {string}
  63103. */
  63104. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  63105. /**
  63106. * The output strength of the SSAO post-process. Default value is 1.0.
  63107. * @type {number}
  63108. */
  63109. _this.totalStrength = 1.0;
  63110. /**
  63111. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  63112. * @type {number}
  63113. */
  63114. _this.maxZ = 100.0;
  63115. /**
  63116. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  63117. * @type {number}
  63118. */
  63119. _this.minZAspect = 0.2;
  63120. /**
  63121. * Number of samples used for the SSAO calculations. Default value is 8
  63122. * @type {number}
  63123. */
  63124. _this._samples = 8;
  63125. /**
  63126. * Are we using bilateral blur ?
  63127. * @type {boolean}
  63128. */
  63129. _this._expensiveBlur = true;
  63130. /**
  63131. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  63132. * @type {number}
  63133. */
  63134. _this.radius = 2.0;
  63135. /**
  63136. * The base color of the SSAO post-process
  63137. * The final result is "base + ssao" between [0, 1]
  63138. * @type {number}
  63139. */
  63140. _this.base = 0.1;
  63141. _this._firstUpdate = true;
  63142. _this._scene = scene;
  63143. if (!_this.isSupported) {
  63144. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  63145. return _this;
  63146. }
  63147. var ssaoRatio = ratio.ssaoRatio || ratio;
  63148. var blurRatio = ratio.blurRatio || ratio;
  63149. // Set up assets
  63150. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  63151. _this._createRandomTexture();
  63152. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  63153. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  63154. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  63155. _this._createSSAOPostProcess(1.0);
  63156. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  63157. _this._createSSAOCombinePostProcess(blurRatio);
  63158. // Set up pipeline
  63159. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  63160. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  63161. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  63162. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  63163. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  63164. // Finish
  63165. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63166. if (cameras)
  63167. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63168. return _this;
  63169. }
  63170. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  63171. get: function () {
  63172. return this._samples;
  63173. },
  63174. set: function (n) {
  63175. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  63176. this._samples = n;
  63177. this._sampleSphere = this._generateHemisphere();
  63178. this._firstUpdate = true;
  63179. },
  63180. enumerable: true,
  63181. configurable: true
  63182. });
  63183. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  63184. get: function () {
  63185. return this._expensiveBlur;
  63186. },
  63187. set: function (b) {
  63188. 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"]);
  63189. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  63190. this._expensiveBlur = b;
  63191. this._firstUpdate = true;
  63192. },
  63193. enumerable: true,
  63194. configurable: true
  63195. });
  63196. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  63197. /**
  63198. * Support test.
  63199. * @type {boolean}
  63200. */
  63201. get: function () {
  63202. var engine = BABYLON.Engine.LastCreatedEngine;
  63203. if (!engine) {
  63204. return false;
  63205. }
  63206. return engine.getCaps().drawBuffersExtension;
  63207. },
  63208. enumerable: true,
  63209. configurable: true
  63210. });
  63211. // Public Methods
  63212. /**
  63213. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63214. */
  63215. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  63216. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  63217. for (var i = 0; i < this._scene.cameras.length; i++) {
  63218. var camera = this._scene.cameras[i];
  63219. this._originalColorPostProcess.dispose(camera);
  63220. this._ssaoPostProcess.dispose(camera);
  63221. this._blurHPostProcess.dispose(camera);
  63222. this._blurVPostProcess.dispose(camera);
  63223. this._ssaoCombinePostProcess.dispose(camera);
  63224. }
  63225. this._randomTexture.dispose();
  63226. if (disableGeometryBufferRenderer)
  63227. this._scene.disableGeometryBufferRenderer();
  63228. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63229. _super.prototype.dispose.call(this);
  63230. };
  63231. // Private Methods
  63232. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  63233. var _this = this;
  63234. this._samplerOffsets = [];
  63235. var expensive = this.expensiveBlur;
  63236. for (var i = -8; i < 8; i++) {
  63237. this._samplerOffsets.push(i * 2 + 0.5);
  63238. }
  63239. 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");
  63240. this._blurHPostProcess.onApply = function (effect) {
  63241. if (!_this._scene.activeCamera) {
  63242. return;
  63243. }
  63244. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  63245. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63246. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63247. effect.setFloat("radius", _this.radius);
  63248. effect.setTexture("depthSampler", _this._depthTexture);
  63249. if (_this._firstUpdate) {
  63250. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63251. }
  63252. };
  63253. 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");
  63254. this._blurVPostProcess.onApply = function (effect) {
  63255. if (!_this._scene.activeCamera) {
  63256. return;
  63257. }
  63258. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  63259. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63260. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63261. effect.setFloat("radius", _this.radius);
  63262. effect.setTexture("depthSampler", _this._depthTexture);
  63263. if (_this._firstUpdate) {
  63264. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63265. _this._firstUpdate = false;
  63266. }
  63267. };
  63268. };
  63269. SSAO2RenderingPipeline.prototype._rebuild = function () {
  63270. this._firstUpdate = true;
  63271. _super.prototype._rebuild.call(this);
  63272. };
  63273. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  63274. var numSamples = this.samples;
  63275. var result = [];
  63276. var vector, scale;
  63277. var rand = function (min, max) {
  63278. return Math.random() * (max - min) + min;
  63279. };
  63280. var i = 0;
  63281. while (i < numSamples) {
  63282. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  63283. vector.normalize();
  63284. scale = i / numSamples;
  63285. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  63286. vector.scaleInPlace(scale);
  63287. result.push(vector.x, vector.y, vector.z);
  63288. i++;
  63289. }
  63290. return result;
  63291. };
  63292. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63293. var _this = this;
  63294. var numSamples = this.samples;
  63295. this._sampleSphere = this._generateHemisphere();
  63296. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  63297. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63298. "base", "range", "projection", "near", "far", "texelSize",
  63299. "xViewport", "yViewport", "maxZ", "minZAspect"
  63300. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63301. this._ssaoPostProcess.onApply = function (effect) {
  63302. if (_this._firstUpdate) {
  63303. effect.setArray3("sampleSphere", _this._sampleSphere);
  63304. effect.setFloat("randTextureTiles", 4.0);
  63305. }
  63306. if (!_this._scene.activeCamera) {
  63307. return;
  63308. }
  63309. effect.setFloat("samplesFactor", 1 / _this.samples);
  63310. effect.setFloat("totalStrength", _this.totalStrength);
  63311. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  63312. effect.setFloat("radius", _this.radius);
  63313. effect.setFloat("maxZ", _this.maxZ);
  63314. effect.setFloat("minZAspect", _this.minZAspect);
  63315. effect.setFloat("base", _this.base);
  63316. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63317. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63318. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  63319. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  63320. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  63321. effect.setTexture("textureSampler", _this._depthTexture);
  63322. effect.setTexture("normalSampler", _this._normalTexture);
  63323. effect.setTexture("randomSampler", _this._randomTexture);
  63324. };
  63325. };
  63326. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63327. var _this = this;
  63328. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63329. this._ssaoCombinePostProcess.onApply = function (effect) {
  63330. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63331. };
  63332. };
  63333. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  63334. var size = 512;
  63335. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63336. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63337. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63338. var context = this._randomTexture.getContext();
  63339. var rand = function (min, max) {
  63340. return Math.random() * (max - min) + min;
  63341. };
  63342. var randVector = BABYLON.Vector3.Zero();
  63343. for (var x = 0; x < size; x++) {
  63344. for (var y = 0; y < size; y++) {
  63345. randVector.x = rand(0.0, 1.0);
  63346. randVector.y = rand(0.0, 1.0);
  63347. randVector.z = 0.0;
  63348. randVector.normalize();
  63349. randVector.scaleInPlace(255);
  63350. randVector.x = Math.floor(randVector.x);
  63351. randVector.y = Math.floor(randVector.y);
  63352. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63353. context.fillRect(x, y, 1, 1);
  63354. }
  63355. }
  63356. this._randomTexture.update(false);
  63357. };
  63358. __decorate([
  63359. BABYLON.serialize()
  63360. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  63361. __decorate([
  63362. BABYLON.serialize()
  63363. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  63364. __decorate([
  63365. BABYLON.serialize()
  63366. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  63367. __decorate([
  63368. BABYLON.serialize("samples")
  63369. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  63370. __decorate([
  63371. BABYLON.serialize("expensiveBlur")
  63372. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  63373. __decorate([
  63374. BABYLON.serialize()
  63375. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  63376. __decorate([
  63377. BABYLON.serialize()
  63378. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  63379. return SSAO2RenderingPipeline;
  63380. }(BABYLON.PostProcessRenderPipeline));
  63381. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  63382. })(BABYLON || (BABYLON = {}));
  63383. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  63384. // BABYLON.JS Chromatic Aberration GLSL Shader
  63385. // Author: Olivier Guyot
  63386. // Separates very slightly R, G and B colors on the edges of the screen
  63387. // Inspired by Francois Tarlier & Martins Upitis
  63388. var BABYLON;
  63389. (function (BABYLON) {
  63390. var LensRenderingPipeline = /** @class */ (function (_super) {
  63391. __extends(LensRenderingPipeline, _super);
  63392. /**
  63393. * @constructor
  63394. *
  63395. * Effect parameters are as follow:
  63396. * {
  63397. * chromatic_aberration: number; // from 0 to x (1 for realism)
  63398. * edge_blur: number; // from 0 to x (1 for realism)
  63399. * distortion: number; // from 0 to x (1 for realism)
  63400. * grain_amount: number; // from 0 to 1
  63401. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  63402. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  63403. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  63404. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  63405. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  63406. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  63407. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  63408. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  63409. * }
  63410. * Note: if an effect parameter is unset, effect is disabled
  63411. *
  63412. * @param {string} name - The rendering pipeline name
  63413. * @param {object} parameters - An object containing all parameters (see above)
  63414. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63415. * @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)
  63416. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63417. */
  63418. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  63419. if (ratio === void 0) { ratio = 1.0; }
  63420. var _this = _super.call(this, scene.getEngine(), name) || this;
  63421. // Lens effects can be of the following:
  63422. // - chromatic aberration (slight shift of RGB colors)
  63423. // - blur on the edge of the lens
  63424. // - lens distortion
  63425. // - depth-of-field blur & highlights enhancing
  63426. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  63427. // - grain effect (noise or custom texture)
  63428. // Two additional texture samplers are needed:
  63429. // - depth map (for depth-of-field)
  63430. // - grain texture
  63431. /**
  63432. * The chromatic aberration PostProcess id in the pipeline
  63433. * @type {string}
  63434. */
  63435. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  63436. /**
  63437. * The highlights enhancing PostProcess id in the pipeline
  63438. * @type {string}
  63439. */
  63440. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  63441. /**
  63442. * The depth-of-field PostProcess id in the pipeline
  63443. * @type {string}
  63444. */
  63445. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  63446. _this._scene = scene;
  63447. // Fetch texture samplers
  63448. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63449. if (parameters.grain_texture) {
  63450. _this._grainTexture = parameters.grain_texture;
  63451. }
  63452. else {
  63453. _this._createGrainTexture();
  63454. }
  63455. // save parameters
  63456. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  63457. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  63458. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  63459. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  63460. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  63461. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  63462. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  63463. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  63464. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  63465. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  63466. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  63467. // Create effects
  63468. _this._createChromaticAberrationPostProcess(ratio);
  63469. _this._createHighlightsPostProcess(ratio);
  63470. _this._createDepthOfFieldPostProcess(ratio / 4);
  63471. // Set up pipeline
  63472. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  63473. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  63474. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  63475. if (_this._highlightsGain === -1) {
  63476. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  63477. }
  63478. // Finish
  63479. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63480. if (cameras) {
  63481. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63482. }
  63483. return _this;
  63484. }
  63485. // public methods (self explanatory)
  63486. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  63487. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  63488. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  63489. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  63490. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  63491. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  63492. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  63493. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  63494. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  63495. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  63496. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  63497. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  63498. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  63499. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  63500. };
  63501. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  63502. this._highlightsPostProcess.updateEffect();
  63503. };
  63504. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  63505. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  63506. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  63507. this._highlightsGain = amount;
  63508. };
  63509. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  63510. if (this._highlightsGain === -1) {
  63511. this._highlightsGain = 1.0;
  63512. }
  63513. this._highlightsThreshold = amount;
  63514. };
  63515. LensRenderingPipeline.prototype.disableHighlights = function () {
  63516. this._highlightsGain = -1;
  63517. };
  63518. /**
  63519. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  63520. */
  63521. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63522. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63523. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63524. this._chromaticAberrationPostProcess = null;
  63525. this._highlightsPostProcess = null;
  63526. this._depthOfFieldPostProcess = null;
  63527. this._grainTexture.dispose();
  63528. if (disableDepthRender)
  63529. this._scene.disableDepthRenderer();
  63530. };
  63531. // colors shifting and distortion
  63532. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  63533. var _this = this;
  63534. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  63535. [], // samplers
  63536. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63537. this._chromaticAberrationPostProcess.onApply = function (effect) {
  63538. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  63539. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63540. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63541. };
  63542. };
  63543. // highlights enhancing
  63544. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  63545. var _this = this;
  63546. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  63547. [], // samplers
  63548. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  63549. this._highlightsPostProcess.onApply = function (effect) {
  63550. effect.setFloat('gain', _this._highlightsGain);
  63551. effect.setFloat('threshold', _this._highlightsThreshold);
  63552. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  63553. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63554. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63555. };
  63556. };
  63557. // colors shifting and distortion
  63558. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  63559. var _this = this;
  63560. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  63561. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  63562. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  63563. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63564. this._depthOfFieldPostProcess.onApply = function (effect) {
  63565. effect.setTexture("depthSampler", _this._depthTexture);
  63566. effect.setTexture("grainSampler", _this._grainTexture);
  63567. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  63568. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  63569. effect.setFloat('grain_amount', _this._grainAmount);
  63570. effect.setBool('blur_noise', _this._blurNoise);
  63571. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63572. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63573. effect.setFloat('distortion', _this._distortion);
  63574. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63575. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63576. effect.setFloat('aperture', _this._dofAperture);
  63577. effect.setFloat('darken', _this._dofDarken);
  63578. effect.setFloat('edge_blur', _this._edgeBlur);
  63579. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63580. if (_this._scene.activeCamera) {
  63581. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63582. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63583. }
  63584. };
  63585. };
  63586. // creates a black and white random noise texture, 512x512
  63587. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63588. var size = 512;
  63589. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63590. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63591. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63592. var context = this._grainTexture.getContext();
  63593. var rand = function (min, max) {
  63594. return Math.random() * (max - min) + min;
  63595. };
  63596. var value;
  63597. for (var x = 0; x < size; x++) {
  63598. for (var y = 0; y < size; y++) {
  63599. value = Math.floor(rand(0.42, 0.58) * 255);
  63600. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63601. context.fillRect(x, y, 1, 1);
  63602. }
  63603. }
  63604. this._grainTexture.update(false);
  63605. };
  63606. return LensRenderingPipeline;
  63607. }(BABYLON.PostProcessRenderPipeline));
  63608. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63609. })(BABYLON || (BABYLON = {}));
  63610. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63611. var BABYLON;
  63612. (function (BABYLON) {
  63613. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63614. __extends(StandardRenderingPipeline, _super);
  63615. /**
  63616. * @constructor
  63617. * @param {string} name - The rendering pipeline name
  63618. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63619. * @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)
  63620. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63621. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63622. */
  63623. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63624. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63625. var _this = _super.call(this, scene.getEngine(), name) || this;
  63626. _this.downSampleX4PostProcess = null;
  63627. _this.brightPassPostProcess = null;
  63628. _this.blurHPostProcesses = [];
  63629. _this.blurVPostProcesses = [];
  63630. _this.textureAdderPostProcess = null;
  63631. _this.volumetricLightPostProcess = null;
  63632. _this.volumetricLightSmoothXPostProcess = null;
  63633. _this.volumetricLightSmoothYPostProcess = null;
  63634. _this.volumetricLightMergePostProces = null;
  63635. _this.volumetricLightFinalPostProcess = null;
  63636. _this.luminancePostProcess = null;
  63637. _this.luminanceDownSamplePostProcesses = [];
  63638. _this.hdrPostProcess = null;
  63639. _this.textureAdderFinalPostProcess = null;
  63640. _this.lensFlareFinalPostProcess = null;
  63641. _this.hdrFinalPostProcess = null;
  63642. _this.lensFlarePostProcess = null;
  63643. _this.lensFlareComposePostProcess = null;
  63644. _this.motionBlurPostProcess = null;
  63645. _this.depthOfFieldPostProcess = null;
  63646. // Values
  63647. _this.brightThreshold = 1.0;
  63648. _this.blurWidth = 512.0;
  63649. _this.horizontalBlur = false;
  63650. _this.exposure = 1.0;
  63651. _this.lensTexture = null;
  63652. _this.volumetricLightCoefficient = 0.2;
  63653. _this.volumetricLightPower = 4.0;
  63654. _this.volumetricLightBlurScale = 64.0;
  63655. _this.sourceLight = null;
  63656. _this.hdrMinimumLuminance = 1.0;
  63657. _this.hdrDecreaseRate = 0.5;
  63658. _this.hdrIncreaseRate = 0.5;
  63659. _this.lensColorTexture = null;
  63660. _this.lensFlareStrength = 20.0;
  63661. _this.lensFlareGhostDispersal = 1.4;
  63662. _this.lensFlareHaloWidth = 0.7;
  63663. _this.lensFlareDistortionStrength = 16.0;
  63664. _this.lensStarTexture = null;
  63665. _this.lensFlareDirtTexture = null;
  63666. _this.depthOfFieldDistance = 10.0;
  63667. _this.depthOfFieldBlurWidth = 64.0;
  63668. _this.motionStrength = 1.0;
  63669. // IAnimatable
  63670. _this.animations = [];
  63671. _this._currentDepthOfFieldSource = null;
  63672. _this._hdrCurrentLuminance = 1.0;
  63673. // Getters and setters
  63674. _this._bloomEnabled = true;
  63675. _this._depthOfFieldEnabled = false;
  63676. _this._vlsEnabled = false;
  63677. _this._lensFlareEnabled = false;
  63678. _this._hdrEnabled = false;
  63679. _this._motionBlurEnabled = false;
  63680. _this._motionBlurSamples = 64.0;
  63681. _this._volumetricLightStepsCount = 50.0;
  63682. _this._cameras = cameras || [];
  63683. // Initialize
  63684. _this._scene = scene;
  63685. _this._basePostProcess = originalPostProcess;
  63686. _this._ratio = ratio;
  63687. // Misc
  63688. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63689. // Finish
  63690. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63691. _this._buildPipeline();
  63692. return _this;
  63693. }
  63694. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  63695. get: function () {
  63696. return this._bloomEnabled;
  63697. },
  63698. set: function (enabled) {
  63699. if (this._bloomEnabled === enabled) {
  63700. return;
  63701. }
  63702. this._bloomEnabled = enabled;
  63703. this._buildPipeline();
  63704. },
  63705. enumerable: true,
  63706. configurable: true
  63707. });
  63708. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63709. get: function () {
  63710. return this._depthOfFieldEnabled;
  63711. },
  63712. set: function (enabled) {
  63713. if (this._depthOfFieldEnabled === enabled) {
  63714. return;
  63715. }
  63716. this._depthOfFieldEnabled = enabled;
  63717. this._buildPipeline();
  63718. },
  63719. enumerable: true,
  63720. configurable: true
  63721. });
  63722. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63723. get: function () {
  63724. return this._lensFlareEnabled;
  63725. },
  63726. set: function (enabled) {
  63727. if (this._lensFlareEnabled === enabled) {
  63728. return;
  63729. }
  63730. this._lensFlareEnabled = enabled;
  63731. this._buildPipeline();
  63732. },
  63733. enumerable: true,
  63734. configurable: true
  63735. });
  63736. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  63737. get: function () {
  63738. return this._hdrEnabled;
  63739. },
  63740. set: function (enabled) {
  63741. if (this._hdrEnabled === enabled) {
  63742. return;
  63743. }
  63744. this._hdrEnabled = enabled;
  63745. this._buildPipeline();
  63746. },
  63747. enumerable: true,
  63748. configurable: true
  63749. });
  63750. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  63751. get: function () {
  63752. return this._vlsEnabled;
  63753. },
  63754. set: function (enabled) {
  63755. if (this._vlsEnabled === enabled) {
  63756. return;
  63757. }
  63758. if (enabled) {
  63759. var geometry = this._scene.enableGeometryBufferRenderer();
  63760. if (!geometry) {
  63761. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63762. return;
  63763. }
  63764. }
  63765. this._vlsEnabled = enabled;
  63766. this._buildPipeline();
  63767. },
  63768. enumerable: true,
  63769. configurable: true
  63770. });
  63771. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63772. get: function () {
  63773. return this._motionBlurEnabled;
  63774. },
  63775. set: function (enabled) {
  63776. if (this._motionBlurEnabled === enabled) {
  63777. return;
  63778. }
  63779. this._motionBlurEnabled = enabled;
  63780. this._buildPipeline();
  63781. },
  63782. enumerable: true,
  63783. configurable: true
  63784. });
  63785. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63786. get: function () {
  63787. return this._volumetricLightStepsCount;
  63788. },
  63789. set: function (count) {
  63790. if (this.volumetricLightPostProcess) {
  63791. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63792. }
  63793. this._volumetricLightStepsCount = count;
  63794. },
  63795. enumerable: true,
  63796. configurable: true
  63797. });
  63798. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63799. get: function () {
  63800. return this._motionBlurSamples;
  63801. },
  63802. set: function (samples) {
  63803. if (this.motionBlurPostProcess) {
  63804. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63805. }
  63806. this._motionBlurSamples = samples;
  63807. },
  63808. enumerable: true,
  63809. configurable: true
  63810. });
  63811. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63812. var _this = this;
  63813. var ratio = this._ratio;
  63814. var scene = this._scene;
  63815. this._disposePostProcesses();
  63816. this._reset();
  63817. // Create pass post-process
  63818. if (!this._basePostProcess) {
  63819. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63820. this.originalPostProcess.onApply = function (effect) {
  63821. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63822. };
  63823. }
  63824. else {
  63825. this.originalPostProcess = this._basePostProcess;
  63826. }
  63827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63828. this._currentDepthOfFieldSource = this.originalPostProcess;
  63829. if (this._vlsEnabled) {
  63830. // Create volumetric light
  63831. this._createVolumetricLightPostProcess(scene, ratio);
  63832. // Create volumetric light final post-process
  63833. 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);
  63834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63835. }
  63836. if (this._bloomEnabled) {
  63837. // Create down sample X4 post-process
  63838. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63839. // Create bright pass post-process
  63840. this._createBrightPassPostProcess(scene, ratio / 2);
  63841. // Create gaussian blur post-processes (down sampling blurs)
  63842. this._createBlurPostProcesses(scene, ratio / 4, 1);
  63843. // Create texture adder post-process
  63844. this._createTextureAdderPostProcess(scene, ratio);
  63845. // Create depth-of-field source post-process
  63846. 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);
  63847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63848. }
  63849. if (this._lensFlareEnabled) {
  63850. // Create lens flare post-process
  63851. this._createLensFlarePostProcess(scene, ratio);
  63852. // Create depth-of-field source post-process post lens-flare and disable it now
  63853. 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);
  63854. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  63855. }
  63856. if (this._hdrEnabled) {
  63857. // Create luminance
  63858. this._createLuminancePostProcesses(scene, this._floatTextureType);
  63859. // Create HDR
  63860. this._createHdrPostProcess(scene, ratio);
  63861. // Create depth-of-field source post-process post hdr and disable it now
  63862. 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);
  63863. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  63864. }
  63865. if (this._depthOfFieldEnabled) {
  63866. // Create gaussian blur used by depth-of-field
  63867. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  63868. // Create depth-of-field post-process
  63869. this._createDepthOfFieldPostProcess(scene, ratio);
  63870. }
  63871. if (this._motionBlurEnabled) {
  63872. // Create motion blur post-process
  63873. this._createMotionBlurPostProcess(scene, ratio);
  63874. }
  63875. if (this._cameras !== null) {
  63876. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63877. }
  63878. };
  63879. // Down Sample X4 Post-Processs
  63880. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63881. var _this = this;
  63882. var downSampleX4Offsets = new Array(32);
  63883. 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);
  63884. this.downSampleX4PostProcess.onApply = function (effect) {
  63885. var id = 0;
  63886. var width = _this.downSampleX4PostProcess.width;
  63887. var height = _this.downSampleX4PostProcess.height;
  63888. for (var i = -2; i < 2; i++) {
  63889. for (var j = -2; j < 2; j++) {
  63890. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  63891. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  63892. id += 2;
  63893. }
  63894. }
  63895. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63896. };
  63897. // Add to pipeline
  63898. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63899. };
  63900. // Brightpass Post-Process
  63901. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63902. var _this = this;
  63903. var brightOffsets = new Array(8);
  63904. 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);
  63905. this.brightPassPostProcess.onApply = function (effect) {
  63906. var sU = (1.0 / _this.brightPassPostProcess.width);
  63907. var sV = (1.0 / _this.brightPassPostProcess.height);
  63908. brightOffsets[0] = -0.5 * sU;
  63909. brightOffsets[1] = 0.5 * sV;
  63910. brightOffsets[2] = 0.5 * sU;
  63911. brightOffsets[3] = 0.5 * sV;
  63912. brightOffsets[4] = -0.5 * sU;
  63913. brightOffsets[5] = -0.5 * sV;
  63914. brightOffsets[6] = 0.5 * sU;
  63915. brightOffsets[7] = -0.5 * sV;
  63916. effect.setArray2("dsOffsets", brightOffsets);
  63917. effect.setFloat("brightThreshold", _this.brightThreshold);
  63918. };
  63919. // Add to pipeline
  63920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63921. };
  63922. // Create blur H&V post-processes
  63923. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63924. var _this = this;
  63925. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63926. var engine = scene.getEngine();
  63927. 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);
  63928. 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);
  63929. blurX.onActivateObservable.add(function () {
  63930. var dw = blurX.width / engine.getRenderWidth();
  63931. blurX.kernel = _this[blurWidthKey] * dw;
  63932. });
  63933. blurY.onActivateObservable.add(function () {
  63934. var dw = blurY.height / engine.getRenderHeight();
  63935. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63936. });
  63937. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63939. this.blurHPostProcesses.push(blurX);
  63940. this.blurVPostProcesses.push(blurY);
  63941. };
  63942. // Create texture adder post-process
  63943. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63944. var _this = this;
  63945. 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);
  63946. this.textureAdderPostProcess.onApply = function (effect) {
  63947. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63948. effect.setTexture("lensSampler", _this.lensTexture);
  63949. effect.setFloat("exposure", _this.exposure);
  63950. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63951. };
  63952. // Add to pipeline
  63953. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63954. };
  63955. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63956. var _this = this;
  63957. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63958. geometryRenderer.enablePosition = true;
  63959. var geometry = geometryRenderer.getGBuffer();
  63960. // Base post-process
  63961. 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));
  63962. var depthValues = BABYLON.Vector2.Zero();
  63963. this.volumetricLightPostProcess.onApply = function (effect) {
  63964. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63965. var generator = _this.sourceLight.getShadowGenerator();
  63966. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63967. effect.setTexture("positionSampler", geometry.textures[2]);
  63968. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63969. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63970. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63971. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63972. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63973. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63974. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63975. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63976. effect.setVector2("depthValues", depthValues);
  63977. }
  63978. };
  63979. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63980. // Smooth
  63981. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63982. // Merge
  63983. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63984. this.volumetricLightMergePostProces.onApply = function (effect) {
  63985. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63986. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63987. };
  63988. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63989. };
  63990. // Create luminance
  63991. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63992. var _this = this;
  63993. // Create luminance
  63994. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63995. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63996. var offsets = [];
  63997. this.luminancePostProcess.onApply = function (effect) {
  63998. var sU = (1.0 / _this.luminancePostProcess.width);
  63999. var sV = (1.0 / _this.luminancePostProcess.height);
  64000. offsets[0] = -0.5 * sU;
  64001. offsets[1] = 0.5 * sV;
  64002. offsets[2] = 0.5 * sU;
  64003. offsets[3] = 0.5 * sV;
  64004. offsets[4] = -0.5 * sU;
  64005. offsets[5] = -0.5 * sV;
  64006. offsets[6] = 0.5 * sU;
  64007. offsets[7] = -0.5 * sV;
  64008. effect.setArray2("lumOffsets", offsets);
  64009. };
  64010. // Add to pipeline
  64011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  64012. // Create down sample luminance
  64013. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  64014. var size = Math.pow(3, i);
  64015. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  64016. if (i === 0) {
  64017. defines += "#define FINAL_DOWN_SAMPLER";
  64018. }
  64019. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  64020. this.luminanceDownSamplePostProcesses.push(postProcess);
  64021. }
  64022. // Create callbacks and add effects
  64023. var lastLuminance = this.luminancePostProcess;
  64024. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  64025. var downSampleOffsets = new Array(18);
  64026. pp.onApply = function (effect) {
  64027. if (!lastLuminance) {
  64028. return;
  64029. }
  64030. var id = 0;
  64031. for (var x = -1; x < 2; x++) {
  64032. for (var y = -1; y < 2; y++) {
  64033. downSampleOffsets[id] = x / lastLuminance.width;
  64034. downSampleOffsets[id + 1] = y / lastLuminance.height;
  64035. id += 2;
  64036. }
  64037. }
  64038. effect.setArray2("dsOffsets", downSampleOffsets);
  64039. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  64040. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64041. lastLuminance = _this.luminancePostProcess;
  64042. }
  64043. else {
  64044. lastLuminance = pp;
  64045. }
  64046. };
  64047. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64048. pp.onAfterRender = function (effect) {
  64049. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  64050. 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);
  64051. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  64052. };
  64053. }
  64054. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  64055. });
  64056. };
  64057. // Create HDR post-process
  64058. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  64059. var _this = this;
  64060. 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);
  64061. var outputLiminance = 1;
  64062. var time = 0;
  64063. var lastTime = 0;
  64064. this.hdrPostProcess.onApply = function (effect) {
  64065. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  64066. time += scene.getEngine().getDeltaTime();
  64067. if (outputLiminance < 0) {
  64068. outputLiminance = _this._hdrCurrentLuminance;
  64069. }
  64070. else {
  64071. var dt = (lastTime - time) / 1000.0;
  64072. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  64073. outputLiminance += _this.hdrDecreaseRate * dt;
  64074. }
  64075. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  64076. outputLiminance -= _this.hdrIncreaseRate * dt;
  64077. }
  64078. else {
  64079. outputLiminance = _this._hdrCurrentLuminance;
  64080. }
  64081. }
  64082. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  64083. effect.setFloat("averageLuminance", outputLiminance);
  64084. lastTime = time;
  64085. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  64086. };
  64087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  64088. };
  64089. // Create lens flare post-process
  64090. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  64091. var _this = this;
  64092. 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);
  64093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  64094. this._createBlurPostProcesses(scene, ratio / 4, 2);
  64095. 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);
  64096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  64097. var resolution = new BABYLON.Vector2(0, 0);
  64098. // Lens flare
  64099. this.lensFlarePostProcess.onApply = function (effect) {
  64100. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  64101. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  64102. effect.setFloat("strength", _this.lensFlareStrength);
  64103. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  64104. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  64105. // Shift
  64106. resolution.x = _this.lensFlarePostProcess.width;
  64107. resolution.y = _this.lensFlarePostProcess.height;
  64108. effect.setVector2("resolution", resolution);
  64109. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  64110. };
  64111. // Compose
  64112. 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);
  64113. 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);
  64114. this.lensFlareComposePostProcess.onApply = function (effect) {
  64115. if (!_this._scene.activeCamera) {
  64116. return;
  64117. }
  64118. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64119. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  64120. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  64121. // Lens start rotation matrix
  64122. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  64123. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  64124. 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));
  64125. camRot *= 4.0;
  64126. 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);
  64127. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  64128. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  64129. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  64130. };
  64131. };
  64132. // Create depth-of-field post-process
  64133. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  64134. var _this = this;
  64135. 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);
  64136. this.depthOfFieldPostProcess.onApply = function (effect) {
  64137. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64138. effect.setTexture("depthSampler", _this._getDepthTexture());
  64139. effect.setFloat("distance", _this.depthOfFieldDistance);
  64140. };
  64141. // Add to pipeline
  64142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  64143. };
  64144. // Create motion blur post-process
  64145. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  64146. var _this = this;
  64147. 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);
  64148. var motionScale = 0;
  64149. var prevViewProjection = BABYLON.Matrix.Identity();
  64150. var invViewProjection = BABYLON.Matrix.Identity();
  64151. var viewProjection = BABYLON.Matrix.Identity();
  64152. var screenSize = BABYLON.Vector2.Zero();
  64153. this.motionBlurPostProcess.onApply = function (effect) {
  64154. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  64155. viewProjection.invertToRef(invViewProjection);
  64156. effect.setMatrix("inverseViewProjection", invViewProjection);
  64157. effect.setMatrix("prevViewProjection", prevViewProjection);
  64158. prevViewProjection = viewProjection;
  64159. screenSize.x = _this.motionBlurPostProcess.width;
  64160. screenSize.y = _this.motionBlurPostProcess.height;
  64161. effect.setVector2("screenSize", screenSize);
  64162. motionScale = scene.getEngine().getFps() / 60.0;
  64163. effect.setFloat("motionScale", motionScale);
  64164. effect.setFloat("motionStrength", _this.motionStrength);
  64165. effect.setTexture("depthSampler", _this._getDepthTexture());
  64166. };
  64167. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  64168. };
  64169. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  64170. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  64171. var renderer = this._scene.enableGeometryBufferRenderer();
  64172. return renderer.getGBuffer().textures[0];
  64173. }
  64174. return this._scene.enableDepthRenderer().getDepthMap();
  64175. };
  64176. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  64177. for (var i = 0; i < this._cameras.length; i++) {
  64178. var camera = this._cameras[i];
  64179. if (this.originalPostProcess) {
  64180. this.originalPostProcess.dispose(camera);
  64181. }
  64182. if (this.downSampleX4PostProcess) {
  64183. this.downSampleX4PostProcess.dispose(camera);
  64184. }
  64185. if (this.brightPassPostProcess) {
  64186. this.brightPassPostProcess.dispose(camera);
  64187. }
  64188. if (this.textureAdderPostProcess) {
  64189. this.textureAdderPostProcess.dispose(camera);
  64190. }
  64191. if (this.textureAdderFinalPostProcess) {
  64192. this.textureAdderFinalPostProcess.dispose(camera);
  64193. }
  64194. if (this.volumetricLightPostProcess) {
  64195. this.volumetricLightPostProcess.dispose(camera);
  64196. }
  64197. if (this.volumetricLightSmoothXPostProcess) {
  64198. this.volumetricLightSmoothXPostProcess.dispose(camera);
  64199. }
  64200. if (this.volumetricLightSmoothYPostProcess) {
  64201. this.volumetricLightSmoothYPostProcess.dispose(camera);
  64202. }
  64203. if (this.volumetricLightMergePostProces) {
  64204. this.volumetricLightMergePostProces.dispose(camera);
  64205. }
  64206. if (this.volumetricLightFinalPostProcess) {
  64207. this.volumetricLightFinalPostProcess.dispose(camera);
  64208. }
  64209. if (this.lensFlarePostProcess) {
  64210. this.lensFlarePostProcess.dispose(camera);
  64211. }
  64212. if (this.lensFlareComposePostProcess) {
  64213. this.lensFlareComposePostProcess.dispose(camera);
  64214. }
  64215. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  64216. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  64217. }
  64218. if (this.luminancePostProcess) {
  64219. this.luminancePostProcess.dispose(camera);
  64220. }
  64221. if (this.hdrPostProcess) {
  64222. this.hdrPostProcess.dispose(camera);
  64223. }
  64224. if (this.hdrFinalPostProcess) {
  64225. this.hdrFinalPostProcess.dispose(camera);
  64226. }
  64227. if (this.depthOfFieldPostProcess) {
  64228. this.depthOfFieldPostProcess.dispose(camera);
  64229. }
  64230. if (this.motionBlurPostProcess) {
  64231. this.motionBlurPostProcess.dispose(camera);
  64232. }
  64233. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  64234. this.blurHPostProcesses[j].dispose(camera);
  64235. }
  64236. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  64237. this.blurVPostProcesses[j].dispose(camera);
  64238. }
  64239. }
  64240. this.originalPostProcess = null;
  64241. this.downSampleX4PostProcess = null;
  64242. this.brightPassPostProcess = null;
  64243. this.textureAdderPostProcess = null;
  64244. this.textureAdderFinalPostProcess = null;
  64245. this.volumetricLightPostProcess = null;
  64246. this.volumetricLightSmoothXPostProcess = null;
  64247. this.volumetricLightSmoothYPostProcess = null;
  64248. this.volumetricLightMergePostProces = null;
  64249. this.volumetricLightFinalPostProcess = null;
  64250. this.lensFlarePostProcess = null;
  64251. this.lensFlareComposePostProcess = null;
  64252. this.luminancePostProcess = null;
  64253. this.hdrPostProcess = null;
  64254. this.hdrFinalPostProcess = null;
  64255. this.depthOfFieldPostProcess = null;
  64256. this.motionBlurPostProcess = null;
  64257. this.luminanceDownSamplePostProcesses = [];
  64258. this.blurHPostProcesses = [];
  64259. this.blurVPostProcesses = [];
  64260. };
  64261. // Dispose
  64262. StandardRenderingPipeline.prototype.dispose = function () {
  64263. this._disposePostProcesses();
  64264. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64265. _super.prototype.dispose.call(this);
  64266. };
  64267. // Serialize rendering pipeline
  64268. StandardRenderingPipeline.prototype.serialize = function () {
  64269. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64270. serializationObject.customType = "StandardRenderingPipeline";
  64271. return serializationObject;
  64272. };
  64273. /**
  64274. * Static members
  64275. */
  64276. // Parse serialized pipeline
  64277. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64278. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  64279. };
  64280. // Luminance steps
  64281. StandardRenderingPipeline.LuminanceSteps = 6;
  64282. __decorate([
  64283. BABYLON.serialize()
  64284. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  64285. __decorate([
  64286. BABYLON.serialize()
  64287. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  64288. __decorate([
  64289. BABYLON.serialize()
  64290. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  64291. __decorate([
  64292. BABYLON.serialize()
  64293. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  64294. __decorate([
  64295. BABYLON.serializeAsTexture("lensTexture")
  64296. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  64297. __decorate([
  64298. BABYLON.serialize()
  64299. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  64300. __decorate([
  64301. BABYLON.serialize()
  64302. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  64303. __decorate([
  64304. BABYLON.serialize()
  64305. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  64306. __decorate([
  64307. BABYLON.serialize()
  64308. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  64309. __decorate([
  64310. BABYLON.serialize()
  64311. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  64312. __decorate([
  64313. BABYLON.serialize()
  64314. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  64315. __decorate([
  64316. BABYLON.serializeAsTexture("lensColorTexture")
  64317. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  64318. __decorate([
  64319. BABYLON.serialize()
  64320. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  64321. __decorate([
  64322. BABYLON.serialize()
  64323. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  64324. __decorate([
  64325. BABYLON.serialize()
  64326. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  64327. __decorate([
  64328. BABYLON.serialize()
  64329. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  64330. __decorate([
  64331. BABYLON.serializeAsTexture("lensStarTexture")
  64332. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  64333. __decorate([
  64334. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  64335. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  64336. __decorate([
  64337. BABYLON.serialize()
  64338. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  64339. __decorate([
  64340. BABYLON.serialize()
  64341. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  64342. __decorate([
  64343. BABYLON.serialize()
  64344. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  64345. __decorate([
  64346. BABYLON.serialize()
  64347. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  64348. __decorate([
  64349. BABYLON.serialize()
  64350. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  64351. __decorate([
  64352. BABYLON.serialize()
  64353. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  64354. __decorate([
  64355. BABYLON.serialize()
  64356. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  64357. __decorate([
  64358. BABYLON.serialize()
  64359. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  64360. __decorate([
  64361. BABYLON.serialize()
  64362. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  64363. __decorate([
  64364. BABYLON.serialize()
  64365. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  64366. __decorate([
  64367. BABYLON.serialize()
  64368. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  64369. __decorate([
  64370. BABYLON.serialize()
  64371. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  64372. return StandardRenderingPipeline;
  64373. }(BABYLON.PostProcessRenderPipeline));
  64374. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  64375. })(BABYLON || (BABYLON = {}));
  64376. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  64377. var BABYLON;
  64378. (function (BABYLON) {
  64379. var FxaaPostProcess = /** @class */ (function (_super) {
  64380. __extends(FxaaPostProcess, _super);
  64381. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64382. if (camera === void 0) { camera = null; }
  64383. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64384. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  64385. _this.onApplyObservable.add(function (effect) {
  64386. var texelSize = _this.texelSize;
  64387. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  64388. });
  64389. return _this;
  64390. }
  64391. return FxaaPostProcess;
  64392. }(BABYLON.PostProcess));
  64393. BABYLON.FxaaPostProcess = FxaaPostProcess;
  64394. })(BABYLON || (BABYLON = {}));
  64395. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  64396. var BABYLON;
  64397. (function (BABYLON) {
  64398. /**
  64399. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  64400. */
  64401. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  64402. __extends(CircleOfConfusionPostProcess, _super);
  64403. /**
  64404. * Creates a new instance of @see CircleOfConfusionPostProcess
  64405. * @param name The name of the effect.
  64406. * @param scene The scene the effect belongs to.
  64407. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  64408. * @param options The required width/height ratio to downsize to before computing the render pass.
  64409. * @param camera The camera to apply the render pass to.
  64410. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64411. * @param engine The engine which the post process will be applied. (default: current engine)
  64412. * @param reusable If the post process can be reused on the same frame. (default: false)
  64413. * @param textureType Type of textures used when performing the post process. (default: 0)
  64414. */
  64415. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  64416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64417. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64418. /**
  64419. * 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.
  64420. */
  64421. _this.lensSize = 50;
  64422. /**
  64423. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64424. */
  64425. _this.fStop = 1.4;
  64426. /**
  64427. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64428. */
  64429. _this.focusDistance = 2000;
  64430. /**
  64431. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  64432. */
  64433. _this.focalLength = 50;
  64434. _this.onApplyObservable.add(function (effect) {
  64435. effect.setTexture("depthSampler", depthTexture);
  64436. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  64437. var aperture = _this.lensSize / _this.fStop;
  64438. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  64439. effect.setFloat('focusDistance', _this.focusDistance);
  64440. effect.setFloat('cocPrecalculation', cocPrecalculation);
  64441. if (scene.activeCamera) {
  64442. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64443. }
  64444. });
  64445. return _this;
  64446. }
  64447. return CircleOfConfusionPostProcess;
  64448. }(BABYLON.PostProcess));
  64449. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  64450. })(BABYLON || (BABYLON = {}));
  64451. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  64452. var BABYLON;
  64453. (function (BABYLON) {
  64454. /**
  64455. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  64456. */
  64457. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  64458. __extends(DepthOfFieldMergePostProcess, _super);
  64459. /**
  64460. * Creates a new instance of @see CircleOfConfusionPostProcess
  64461. * @param name The name of the effect.
  64462. * @param original The non-blurred image to be modified
  64463. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  64464. * @param options The required width/height ratio to downsize to before computing the render pass.
  64465. * @param camera The camera to apply the render pass to.
  64466. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64467. * @param engine The engine which the post process will be applied. (default: current engine)
  64468. * @param reusable If the post process can be reused on the same frame. (default: false)
  64469. * @param textureType Type of textures used when performing the post process. (default: 0)
  64470. */
  64471. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  64472. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64473. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64474. _this.onApplyObservable.add(function (effect) {
  64475. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  64476. effect.setTextureFromPostProcess("originalSampler", original);
  64477. });
  64478. return _this;
  64479. }
  64480. return DepthOfFieldMergePostProcess;
  64481. }(BABYLON.PostProcess));
  64482. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  64483. })(BABYLON || (BABYLON = {}));
  64484. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  64485. var BABYLON;
  64486. (function (BABYLON) {
  64487. /**
  64488. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  64489. */
  64490. var DepthOfFieldEffect = /** @class */ (function (_super) {
  64491. __extends(DepthOfFieldEffect, _super);
  64492. /**
  64493. * Creates a new instance of @see DepthOfFieldEffect
  64494. * @param scene The scene the effect belongs to.
  64495. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  64496. */
  64497. function DepthOfFieldEffect(scene, pipelineTextureType) {
  64498. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  64499. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this.circleOfConfusion, _this.depthOfFieldPass, _this.depthOfFieldBlurY, _this.depthOfFieldBlurX, _this.depthOfFieldMerge]; }, true) || this;
  64500. // Enable and get current depth map
  64501. var depthMap = scene.enableDepthRenderer().getDepthMap();
  64502. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  64503. _this.circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64504. // Capture circle of confusion texture
  64505. _this.depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64506. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  64507. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  64508. _this.depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this.circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64509. _this.depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64510. // Merge blurred images with original image based on circleOfConfusion
  64511. _this.depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this.circleOfConfusion, _this.depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64512. return _this;
  64513. }
  64514. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  64515. get: function () {
  64516. return this.depthOfFieldBlurX.kernel;
  64517. },
  64518. /**
  64519. * The size of the kernel to be used for the blur
  64520. */
  64521. set: function (value) {
  64522. this.depthOfFieldBlurX.kernel = value;
  64523. this.depthOfFieldBlurY.kernel = value;
  64524. },
  64525. enumerable: true,
  64526. configurable: true
  64527. });
  64528. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  64529. get: function () {
  64530. return this.circleOfConfusion.focalLength;
  64531. },
  64532. /**
  64533. * The focal the length of the camera used in the effect
  64534. */
  64535. set: function (value) {
  64536. this.circleOfConfusion.focalLength = value;
  64537. },
  64538. enumerable: true,
  64539. configurable: true
  64540. });
  64541. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  64542. get: function () {
  64543. return this.circleOfConfusion.fStop;
  64544. },
  64545. /**
  64546. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64547. */
  64548. set: function (value) {
  64549. this.circleOfConfusion.fStop = value;
  64550. },
  64551. enumerable: true,
  64552. configurable: true
  64553. });
  64554. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  64555. get: function () {
  64556. return this.circleOfConfusion.focusDistance;
  64557. },
  64558. /**
  64559. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64560. */
  64561. set: function (value) {
  64562. this.circleOfConfusion.focusDistance = value;
  64563. },
  64564. enumerable: true,
  64565. configurable: true
  64566. });
  64567. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  64568. get: function () {
  64569. return this.circleOfConfusion.lensSize;
  64570. },
  64571. /**
  64572. * 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.
  64573. */
  64574. set: function (value) {
  64575. this.circleOfConfusion.lensSize = value;
  64576. },
  64577. enumerable: true,
  64578. configurable: true
  64579. });
  64580. /**
  64581. * Disposes each of the internal effects for a given camera.
  64582. * @param camera The camera to dispose the effect on.
  64583. */
  64584. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  64585. this.depthOfFieldPass.dispose(camera);
  64586. this.circleOfConfusion.dispose(camera);
  64587. this.depthOfFieldBlurX.dispose(camera);
  64588. this.depthOfFieldBlurY.dispose(camera);
  64589. this.depthOfFieldMerge.dispose(camera);
  64590. };
  64591. return DepthOfFieldEffect;
  64592. }(BABYLON.PostProcessRenderEffect));
  64593. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  64594. })(BABYLON || (BABYLON = {}));
  64595. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  64596. var BABYLON;
  64597. (function (BABYLON) {
  64598. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  64599. __extends(DefaultRenderingPipeline, _super);
  64600. /**
  64601. * @constructor
  64602. * @param {string} name - The rendering pipeline name
  64603. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64604. * @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)
  64605. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64606. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  64607. */
  64608. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  64609. if (automaticBuild === void 0) { automaticBuild = true; }
  64610. var _this = _super.call(this, scene.getEngine(), name) || this;
  64611. _this.PassPostProcessId = "PassPostProcessEffect";
  64612. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  64613. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  64614. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  64615. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  64616. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  64617. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  64618. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  64619. // IAnimatable
  64620. _this.animations = [];
  64621. // Values
  64622. _this._bloomEnabled = false;
  64623. _this._depthOfFieldEnabled = false;
  64624. _this._fxaaEnabled = false;
  64625. _this._imageProcessingEnabled = true;
  64626. _this._bloomScale = 0.6;
  64627. _this._buildAllowed = true;
  64628. /**
  64629. * Specifies the size of the bloom blur kernel, relative to the final output size
  64630. */
  64631. _this.bloomKernel = 64;
  64632. /**
  64633. * Specifies the weight of the bloom in the final rendering
  64634. */
  64635. _this._bloomWeight = 0.15;
  64636. _this._cameras = cameras || [];
  64637. _this._buildAllowed = automaticBuild;
  64638. // Initialize
  64639. _this._scene = scene;
  64640. var caps = _this._scene.getEngine().getCaps();
  64641. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  64642. // Misc
  64643. if (_this._hdr) {
  64644. if (caps.textureHalfFloatRender) {
  64645. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64646. }
  64647. else if (caps.textureFloatRender) {
  64648. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64649. }
  64650. }
  64651. else {
  64652. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64653. }
  64654. // Attach
  64655. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64656. _this._buildPipeline();
  64657. return _this;
  64658. }
  64659. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  64660. get: function () {
  64661. return this._bloomWeight;
  64662. },
  64663. set: function (value) {
  64664. if (this._bloomWeight === value) {
  64665. return;
  64666. }
  64667. this._bloomWeight = value;
  64668. if (this._hdr && this.copyBack) {
  64669. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  64670. }
  64671. },
  64672. enumerable: true,
  64673. configurable: true
  64674. });
  64675. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  64676. get: function () {
  64677. return this._bloomScale;
  64678. },
  64679. set: function (value) {
  64680. if (this._bloomScale === value) {
  64681. return;
  64682. }
  64683. this._bloomScale = value;
  64684. this._buildPipeline();
  64685. },
  64686. enumerable: true,
  64687. configurable: true
  64688. });
  64689. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  64690. get: function () {
  64691. return this._bloomEnabled;
  64692. },
  64693. set: function (enabled) {
  64694. if (this._bloomEnabled === enabled) {
  64695. return;
  64696. }
  64697. this._bloomEnabled = enabled;
  64698. this._buildPipeline();
  64699. },
  64700. enumerable: true,
  64701. configurable: true
  64702. });
  64703. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  64704. /**
  64705. * If the depth of field is enabled.
  64706. */
  64707. get: function () {
  64708. return this._depthOfFieldEnabled;
  64709. },
  64710. set: function (enabled) {
  64711. if (this._depthOfFieldEnabled === enabled) {
  64712. return;
  64713. }
  64714. this._depthOfFieldEnabled = enabled;
  64715. this._buildPipeline();
  64716. },
  64717. enumerable: true,
  64718. configurable: true
  64719. });
  64720. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  64721. get: function () {
  64722. return this._fxaaEnabled;
  64723. },
  64724. set: function (enabled) {
  64725. if (this._fxaaEnabled === enabled) {
  64726. return;
  64727. }
  64728. this._fxaaEnabled = enabled;
  64729. this._buildPipeline();
  64730. },
  64731. enumerable: true,
  64732. configurable: true
  64733. });
  64734. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  64735. get: function () {
  64736. return this._imageProcessingEnabled;
  64737. },
  64738. set: function (enabled) {
  64739. if (this._imageProcessingEnabled === enabled) {
  64740. return;
  64741. }
  64742. this._imageProcessingEnabled = enabled;
  64743. this._buildPipeline();
  64744. },
  64745. enumerable: true,
  64746. configurable: true
  64747. });
  64748. /**
  64749. * Force the compilation of the entire pipeline.
  64750. */
  64751. DefaultRenderingPipeline.prototype.prepare = function () {
  64752. var previousState = this._buildAllowed;
  64753. this._buildAllowed = true;
  64754. this._buildPipeline();
  64755. this._buildAllowed = previousState;
  64756. };
  64757. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  64758. var _this = this;
  64759. if (!this._buildAllowed) {
  64760. return;
  64761. }
  64762. var engine = this._scene.getEngine();
  64763. this._disposePostProcesses();
  64764. this._reset();
  64765. if (this.bloomEnabled) {
  64766. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64767. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  64768. if (!this._hdr) {
  64769. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64770. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  64771. this.highlights.autoClear = false;
  64772. this.highlights.alwaysForcePOT = true;
  64773. }
  64774. 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);
  64775. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  64776. this.blurX.alwaysForcePOT = true;
  64777. this.blurX.autoClear = false;
  64778. this.blurX.onActivateObservable.add(function () {
  64779. var dw = _this.blurX.width / engine.getRenderWidth(true);
  64780. _this.blurX.kernel = _this.bloomKernel * dw;
  64781. });
  64782. 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);
  64783. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  64784. this.blurY.alwaysForcePOT = true;
  64785. this.blurY.autoClear = false;
  64786. this.blurY.onActivateObservable.add(function () {
  64787. var dh = _this.blurY.height / engine.getRenderHeight(true);
  64788. _this.blurY.kernel = _this.bloomKernel * dh;
  64789. });
  64790. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64791. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  64792. this.copyBack.alwaysForcePOT = true;
  64793. if (this._hdr) {
  64794. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  64795. var w = this.bloomWeight;
  64796. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  64797. }
  64798. else {
  64799. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  64800. }
  64801. this.copyBack.autoClear = false;
  64802. }
  64803. if (this.depthOfFieldEnabled) {
  64804. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  64805. this.addEffect(this.depthOfField);
  64806. }
  64807. if (this._imageProcessingEnabled) {
  64808. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64809. if (this._hdr) {
  64810. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  64811. }
  64812. else {
  64813. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  64814. }
  64815. }
  64816. if (this.fxaaEnabled) {
  64817. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64818. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  64819. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64820. }
  64821. else if (this._hdr && this.imageProcessing) {
  64822. this.finalMerge = this.imageProcessing;
  64823. }
  64824. else {
  64825. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64826. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  64827. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64828. }
  64829. if (this.bloomEnabled) {
  64830. if (this._hdr) {
  64831. this.copyBack.shareOutputWith(this.blurX);
  64832. if (this.imageProcessing) {
  64833. this.imageProcessing.shareOutputWith(this.pass);
  64834. this.imageProcessing.autoClear = false;
  64835. }
  64836. else if (this.fxaa) {
  64837. this.fxaa.shareOutputWith(this.pass);
  64838. }
  64839. else {
  64840. this.finalMerge.shareOutputWith(this.pass);
  64841. }
  64842. }
  64843. else {
  64844. if (this.fxaa) {
  64845. this.fxaa.shareOutputWith(this.pass);
  64846. }
  64847. else {
  64848. this.finalMerge.shareOutputWith(this.pass);
  64849. }
  64850. }
  64851. }
  64852. if (this._cameras !== null) {
  64853. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64854. }
  64855. };
  64856. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  64857. for (var i = 0; i < this._cameras.length; i++) {
  64858. var camera = this._cameras[i];
  64859. if (this.pass) {
  64860. this.pass.dispose(camera);
  64861. }
  64862. if (this.highlights) {
  64863. this.highlights.dispose(camera);
  64864. }
  64865. if (this.blurX) {
  64866. this.blurX.dispose(camera);
  64867. }
  64868. if (this.blurY) {
  64869. this.blurY.dispose(camera);
  64870. }
  64871. if (this.copyBack) {
  64872. this.copyBack.dispose(camera);
  64873. }
  64874. if (this.imageProcessing) {
  64875. this.imageProcessing.dispose(camera);
  64876. }
  64877. if (this.fxaa) {
  64878. this.fxaa.dispose(camera);
  64879. }
  64880. if (this.finalMerge) {
  64881. this.finalMerge.dispose(camera);
  64882. }
  64883. if (this.depthOfField) {
  64884. this.depthOfField.disposeEffects(camera);
  64885. }
  64886. }
  64887. this.pass = null;
  64888. this.highlights = null;
  64889. this.blurX = null;
  64890. this.blurY = null;
  64891. this.copyBack = null;
  64892. this.imageProcessing = null;
  64893. this.fxaa = null;
  64894. this.finalMerge = null;
  64895. this.depthOfField = null;
  64896. };
  64897. // Dispose
  64898. DefaultRenderingPipeline.prototype.dispose = function () {
  64899. this._disposePostProcesses();
  64900. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64901. _super.prototype.dispose.call(this);
  64902. };
  64903. // Serialize rendering pipeline
  64904. DefaultRenderingPipeline.prototype.serialize = function () {
  64905. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64906. serializationObject.customType = "DefaultRenderingPipeline";
  64907. return serializationObject;
  64908. };
  64909. // Parse serialized pipeline
  64910. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64911. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  64912. };
  64913. __decorate([
  64914. BABYLON.serialize()
  64915. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  64916. __decorate([
  64917. BABYLON.serialize()
  64918. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  64919. __decorate([
  64920. BABYLON.serialize()
  64921. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  64922. __decorate([
  64923. BABYLON.serialize()
  64924. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  64925. __decorate([
  64926. BABYLON.serialize()
  64927. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  64928. __decorate([
  64929. BABYLON.serialize()
  64930. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  64931. __decorate([
  64932. BABYLON.serialize()
  64933. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  64934. __decorate([
  64935. BABYLON.serialize()
  64936. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  64937. __decorate([
  64938. BABYLON.serialize()
  64939. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  64940. return DefaultRenderingPipeline;
  64941. }(BABYLON.PostProcessRenderPipeline));
  64942. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  64943. })(BABYLON || (BABYLON = {}));
  64944. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  64945. var BABYLON;
  64946. (function (BABYLON) {
  64947. /**
  64948. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  64949. */
  64950. var GeometryBufferRenderer = /** @class */ (function () {
  64951. /**
  64952. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  64953. * @param scene The scene the buffer belongs to
  64954. * @param ratio How big is the buffer related to the main canvas.
  64955. */
  64956. function GeometryBufferRenderer(scene, ratio) {
  64957. if (ratio === void 0) { ratio = 1; }
  64958. this._enablePosition = false;
  64959. this._scene = scene;
  64960. this._ratio = ratio;
  64961. // Render target
  64962. this._createRenderTargets();
  64963. }
  64964. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  64965. /**
  64966. * Set the render list (meshes to be rendered) used in the G buffer.
  64967. */
  64968. set: function (meshes) {
  64969. this._multiRenderTarget.renderList = meshes;
  64970. },
  64971. enumerable: true,
  64972. configurable: true
  64973. });
  64974. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  64975. /**
  64976. * Gets wether or not G buffer are supported by the running hardware.
  64977. * This requires draw buffer supports
  64978. */
  64979. get: function () {
  64980. return this._multiRenderTarget.isSupported;
  64981. },
  64982. enumerable: true,
  64983. configurable: true
  64984. });
  64985. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  64986. /**
  64987. * Gets wether or not position are enabled for the G buffer.
  64988. */
  64989. get: function () {
  64990. return this._enablePosition;
  64991. },
  64992. /**
  64993. * Sets wether or not position are enabled for the G buffer.
  64994. */
  64995. set: function (enable) {
  64996. this._enablePosition = enable;
  64997. this.dispose();
  64998. this._createRenderTargets();
  64999. },
  65000. enumerable: true,
  65001. configurable: true
  65002. });
  65003. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  65004. /**
  65005. * Gets the scene associated with the buffer.
  65006. */
  65007. get: function () {
  65008. return this._scene;
  65009. },
  65010. enumerable: true,
  65011. configurable: true
  65012. });
  65013. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  65014. /**
  65015. * Gets the ratio used by the buffer during its creation.
  65016. * How big is the buffer related to the main canvas.
  65017. */
  65018. get: function () {
  65019. return this._ratio;
  65020. },
  65021. enumerable: true,
  65022. configurable: true
  65023. });
  65024. /**
  65025. * Checks wether everything is ready to render a submesh to the G buffer.
  65026. * @param subMesh the submesh to check readiness for
  65027. * @param useInstances is the mesh drawn using instance or not
  65028. * @returns true if ready otherwise false
  65029. */
  65030. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  65031. var material = subMesh.getMaterial();
  65032. if (material && material.disableDepthWrite) {
  65033. return false;
  65034. }
  65035. var defines = [];
  65036. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65037. var mesh = subMesh.getMesh();
  65038. // Alpha test
  65039. if (material && material.needAlphaTesting()) {
  65040. defines.push("#define ALPHATEST");
  65041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65042. attribs.push(BABYLON.VertexBuffer.UVKind);
  65043. defines.push("#define UV1");
  65044. }
  65045. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65047. defines.push("#define UV2");
  65048. }
  65049. }
  65050. // Buffers
  65051. if (this._enablePosition) {
  65052. defines.push("#define POSITION");
  65053. }
  65054. // Bones
  65055. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65056. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65057. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65058. if (mesh.numBoneInfluencers > 4) {
  65059. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65060. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65061. }
  65062. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65063. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65064. }
  65065. else {
  65066. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65067. }
  65068. // Instances
  65069. if (useInstances) {
  65070. defines.push("#define INSTANCES");
  65071. attribs.push("world0");
  65072. attribs.push("world1");
  65073. attribs.push("world2");
  65074. attribs.push("world3");
  65075. }
  65076. // Get correct effect
  65077. var join = defines.join("\n");
  65078. if (this._cachedDefines !== join) {
  65079. this._cachedDefines = join;
  65080. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  65081. }
  65082. return this._effect.isReady();
  65083. };
  65084. /**
  65085. * Gets the current underlying G Buffer.
  65086. * @returns the buffer
  65087. */
  65088. GeometryBufferRenderer.prototype.getGBuffer = function () {
  65089. return this._multiRenderTarget;
  65090. };
  65091. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  65092. /**
  65093. * Gets the number of samples used to render the buffer (anti aliasing).
  65094. */
  65095. get: function () {
  65096. return this._multiRenderTarget.samples;
  65097. },
  65098. /**
  65099. * Sets the number of samples used to render the buffer (anti aliasing).
  65100. */
  65101. set: function (value) {
  65102. this._multiRenderTarget.samples = value;
  65103. },
  65104. enumerable: true,
  65105. configurable: true
  65106. });
  65107. /**
  65108. * Disposes the renderer and frees up associated resources.
  65109. */
  65110. GeometryBufferRenderer.prototype.dispose = function () {
  65111. this.getGBuffer().dispose();
  65112. };
  65113. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  65114. var _this = this;
  65115. var engine = this._scene.getEngine();
  65116. var count = this._enablePosition ? 3 : 2;
  65117. 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 });
  65118. if (!this.isSupported) {
  65119. return;
  65120. }
  65121. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65122. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65123. this._multiRenderTarget.refreshRate = 1;
  65124. this._multiRenderTarget.renderParticles = false;
  65125. this._multiRenderTarget.renderList = null;
  65126. // set default depth value to 1.0 (far away)
  65127. this._multiRenderTarget.onClearObservable.add(function (engine) {
  65128. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  65129. });
  65130. // Custom render function
  65131. var renderSubMesh = function (subMesh) {
  65132. var mesh = subMesh.getRenderingMesh();
  65133. var scene = _this._scene;
  65134. var engine = scene.getEngine();
  65135. var material = subMesh.getMaterial();
  65136. if (!material) {
  65137. return;
  65138. }
  65139. // Culling
  65140. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65141. // Managing instances
  65142. var batch = mesh._getInstancesRenderList(subMesh._id);
  65143. if (batch.mustReturn) {
  65144. return;
  65145. }
  65146. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65147. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  65148. engine.enableEffect(_this._effect);
  65149. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65150. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65151. _this._effect.setMatrix("view", scene.getViewMatrix());
  65152. // Alpha test
  65153. if (material && material.needAlphaTesting()) {
  65154. var alphaTexture = material.getAlphaTestTexture();
  65155. if (alphaTexture) {
  65156. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65157. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65158. }
  65159. }
  65160. // Bones
  65161. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65162. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65163. }
  65164. // Draw
  65165. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65166. }
  65167. };
  65168. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65169. var index;
  65170. if (depthOnlySubMeshes.length) {
  65171. engine.setColorWrite(false);
  65172. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65173. renderSubMesh(depthOnlySubMeshes.data[index]);
  65174. }
  65175. engine.setColorWrite(true);
  65176. }
  65177. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65178. renderSubMesh(opaqueSubMeshes.data[index]);
  65179. }
  65180. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65181. renderSubMesh(alphaTestSubMeshes.data[index]);
  65182. }
  65183. };
  65184. };
  65185. return GeometryBufferRenderer;
  65186. }());
  65187. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  65188. })(BABYLON || (BABYLON = {}));
  65189. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  65190. var BABYLON;
  65191. (function (BABYLON) {
  65192. var RefractionPostProcess = /** @class */ (function (_super) {
  65193. __extends(RefractionPostProcess, _super);
  65194. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  65195. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  65196. _this.color = color;
  65197. _this.depth = depth;
  65198. _this.colorLevel = colorLevel;
  65199. _this.onActivateObservable.add(function (cam) {
  65200. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  65201. });
  65202. _this.onApplyObservable.add(function (effect) {
  65203. effect.setColor3("baseColor", _this.color);
  65204. effect.setFloat("depth", _this.depth);
  65205. effect.setFloat("colorLevel", _this.colorLevel);
  65206. effect.setTexture("refractionSampler", _this._refRexture);
  65207. });
  65208. return _this;
  65209. }
  65210. // Methods
  65211. RefractionPostProcess.prototype.dispose = function (camera) {
  65212. if (this._refRexture) {
  65213. this._refRexture.dispose();
  65214. }
  65215. _super.prototype.dispose.call(this, camera);
  65216. };
  65217. return RefractionPostProcess;
  65218. }(BABYLON.PostProcess));
  65219. BABYLON.RefractionPostProcess = RefractionPostProcess;
  65220. })(BABYLON || (BABYLON = {}));
  65221. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  65222. var BABYLON;
  65223. (function (BABYLON) {
  65224. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  65225. __extends(BlackAndWhitePostProcess, _super);
  65226. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  65227. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  65228. _this.degree = 1;
  65229. _this.onApplyObservable.add(function (effect) {
  65230. effect.setFloat("degree", _this.degree);
  65231. });
  65232. return _this;
  65233. }
  65234. return BlackAndWhitePostProcess;
  65235. }(BABYLON.PostProcess));
  65236. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  65237. })(BABYLON || (BABYLON = {}));
  65238. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  65239. var BABYLON;
  65240. (function (BABYLON) {
  65241. var ConvolutionPostProcess = /** @class */ (function (_super) {
  65242. __extends(ConvolutionPostProcess, _super);
  65243. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  65244. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  65245. _this.kernel = kernel;
  65246. _this.onApply = function (effect) {
  65247. effect.setFloat2("screenSize", _this.width, _this.height);
  65248. effect.setArray("kernel", _this.kernel);
  65249. };
  65250. return _this;
  65251. }
  65252. // Statics
  65253. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  65254. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  65255. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  65256. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  65257. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  65258. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  65259. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  65260. return ConvolutionPostProcess;
  65261. }(BABYLON.PostProcess));
  65262. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  65263. })(BABYLON || (BABYLON = {}));
  65264. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  65265. var BABYLON;
  65266. (function (BABYLON) {
  65267. var FilterPostProcess = /** @class */ (function (_super) {
  65268. __extends(FilterPostProcess, _super);
  65269. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  65270. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  65271. _this.kernelMatrix = kernelMatrix;
  65272. _this.onApply = function (effect) {
  65273. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  65274. };
  65275. return _this;
  65276. }
  65277. return FilterPostProcess;
  65278. }(BABYLON.PostProcess));
  65279. BABYLON.FilterPostProcess = FilterPostProcess;
  65280. })(BABYLON || (BABYLON = {}));
  65281. //# sourceMappingURL=babylon.filterPostProcess.js.map
  65282. var BABYLON;
  65283. (function (BABYLON) {
  65284. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  65285. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  65286. __extends(VolumetricLightScatteringPostProcess, _super);
  65287. /**
  65288. * @constructor
  65289. * @param {string} name - The post-process name
  65290. * @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)
  65291. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  65292. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  65293. * @param {number} samples - The post-process quality, default 100
  65294. * @param {number} samplingMode - The post-process filtering mode
  65295. * @param {BABYLON.Engine} engine - The babylon engine
  65296. * @param {boolean} reusable - If the post-process is reusable
  65297. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  65298. */
  65299. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  65300. if (samples === void 0) { samples = 100; }
  65301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65302. 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;
  65303. _this._screenCoordinates = BABYLON.Vector2.Zero();
  65304. /**
  65305. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  65306. * @type {Vector3}
  65307. */
  65308. _this.customMeshPosition = BABYLON.Vector3.Zero();
  65309. /**
  65310. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  65311. * @type {boolean}
  65312. */
  65313. _this.useCustomMeshPosition = false;
  65314. /**
  65315. * If the post-process should inverse the light scattering direction
  65316. * @type {boolean}
  65317. */
  65318. _this.invert = true;
  65319. /**
  65320. * Array containing the excluded meshes not rendered in the internal pass
  65321. */
  65322. _this.excludedMeshes = new Array();
  65323. /**
  65324. * Controls the overall intensity of the post-process
  65325. * @type {number}
  65326. */
  65327. _this.exposure = 0.3;
  65328. /**
  65329. * Dissipates each sample's contribution in range [0, 1]
  65330. * @type {number}
  65331. */
  65332. _this.decay = 0.96815;
  65333. /**
  65334. * Controls the overall intensity of each sample
  65335. * @type {number}
  65336. */
  65337. _this.weight = 0.58767;
  65338. /**
  65339. * Controls the density of each sample
  65340. * @type {number}
  65341. */
  65342. _this.density = 0.926;
  65343. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  65344. engine = scene.getEngine();
  65345. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  65346. // Configure mesh
  65347. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  65348. // Configure
  65349. _this._createPass(scene, ratio.passRatio || ratio);
  65350. _this.onActivate = function (camera) {
  65351. if (!_this.isSupported) {
  65352. _this.dispose(camera);
  65353. }
  65354. _this.onActivate = null;
  65355. };
  65356. _this.onApplyObservable.add(function (effect) {
  65357. _this._updateMeshScreenCoordinates(scene);
  65358. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  65359. effect.setFloat("exposure", _this.exposure);
  65360. effect.setFloat("decay", _this.decay);
  65361. effect.setFloat("weight", _this.weight);
  65362. effect.setFloat("density", _this.density);
  65363. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  65364. });
  65365. return _this;
  65366. }
  65367. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  65368. get: function () {
  65369. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65370. return false;
  65371. },
  65372. set: function (useDiffuseColor) {
  65373. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65374. },
  65375. enumerable: true,
  65376. configurable: true
  65377. });
  65378. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  65379. return "VolumetricLightScatteringPostProcess";
  65380. };
  65381. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  65382. var mesh = subMesh.getMesh();
  65383. // Render this.mesh as default
  65384. if (mesh === this.mesh && mesh.material) {
  65385. return mesh.material.isReady(mesh);
  65386. }
  65387. var defines = [];
  65388. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65389. var material = subMesh.getMaterial();
  65390. // Alpha test
  65391. if (material) {
  65392. if (material.needAlphaTesting()) {
  65393. defines.push("#define ALPHATEST");
  65394. }
  65395. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65396. attribs.push(BABYLON.VertexBuffer.UVKind);
  65397. defines.push("#define UV1");
  65398. }
  65399. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65400. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65401. defines.push("#define UV2");
  65402. }
  65403. }
  65404. // Bones
  65405. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65406. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65407. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65408. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65409. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  65410. }
  65411. else {
  65412. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65413. }
  65414. // Instances
  65415. if (useInstances) {
  65416. defines.push("#define INSTANCES");
  65417. attribs.push("world0");
  65418. attribs.push("world1");
  65419. attribs.push("world2");
  65420. attribs.push("world3");
  65421. }
  65422. // Get correct effect
  65423. var join = defines.join("\n");
  65424. if (this._cachedDefines !== join) {
  65425. this._cachedDefines = join;
  65426. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  65427. }
  65428. return this._volumetricLightScatteringPass.isReady();
  65429. };
  65430. /**
  65431. * Sets the new light position for light scattering effect
  65432. * @param {BABYLON.Vector3} The new custom light position
  65433. */
  65434. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  65435. this.customMeshPosition = position;
  65436. };
  65437. /**
  65438. * Returns the light position for light scattering effect
  65439. * @return {BABYLON.Vector3} The custom light position
  65440. */
  65441. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  65442. return this.customMeshPosition;
  65443. };
  65444. /**
  65445. * Disposes the internal assets and detaches the post-process from the camera
  65446. */
  65447. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  65448. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  65449. if (rttIndex !== -1) {
  65450. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  65451. }
  65452. this._volumetricLightScatteringRTT.dispose();
  65453. _super.prototype.dispose.call(this, camera);
  65454. };
  65455. /**
  65456. * Returns the render target texture used by the post-process
  65457. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  65458. */
  65459. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  65460. return this._volumetricLightScatteringRTT;
  65461. };
  65462. // Private methods
  65463. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  65464. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  65465. return true;
  65466. }
  65467. return false;
  65468. };
  65469. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  65470. var _this = this;
  65471. var engine = scene.getEngine();
  65472. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65473. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65474. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65475. this._volumetricLightScatteringRTT.renderList = null;
  65476. this._volumetricLightScatteringRTT.renderParticles = false;
  65477. var camera = this.getCamera();
  65478. if (camera) {
  65479. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65480. }
  65481. else {
  65482. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65483. }
  65484. // Custom render function for submeshes
  65485. var renderSubMesh = function (subMesh) {
  65486. var mesh = subMesh.getRenderingMesh();
  65487. if (_this._meshExcluded(mesh)) {
  65488. return;
  65489. }
  65490. var material = subMesh.getMaterial();
  65491. if (!material) {
  65492. return;
  65493. }
  65494. var scene = mesh.getScene();
  65495. var engine = scene.getEngine();
  65496. // Culling
  65497. engine.setState(material.backFaceCulling);
  65498. // Managing instances
  65499. var batch = mesh._getInstancesRenderList(subMesh._id);
  65500. if (batch.mustReturn) {
  65501. return;
  65502. }
  65503. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65504. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  65505. var effect = _this._volumetricLightScatteringPass;
  65506. if (mesh === _this.mesh) {
  65507. if (subMesh.effect) {
  65508. effect = subMesh.effect;
  65509. }
  65510. else {
  65511. effect = material.getEffect();
  65512. }
  65513. }
  65514. engine.enableEffect(effect);
  65515. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  65516. if (mesh === _this.mesh) {
  65517. material.bind(mesh.getWorldMatrix(), mesh);
  65518. }
  65519. else {
  65520. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  65521. // Alpha test
  65522. if (material && material.needAlphaTesting()) {
  65523. var alphaTexture = material.getAlphaTestTexture();
  65524. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  65525. if (alphaTexture) {
  65526. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65527. }
  65528. }
  65529. // Bones
  65530. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65531. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65532. }
  65533. }
  65534. // Draw
  65535. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  65536. }
  65537. };
  65538. // Render target texture callbacks
  65539. var savedSceneClearColor;
  65540. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  65541. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  65542. savedSceneClearColor = scene.clearColor;
  65543. scene.clearColor = sceneClearColor;
  65544. });
  65545. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  65546. scene.clearColor = savedSceneClearColor;
  65547. });
  65548. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65549. var engine = scene.getEngine();
  65550. var index;
  65551. if (depthOnlySubMeshes.length) {
  65552. engine.setColorWrite(false);
  65553. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65554. renderSubMesh(depthOnlySubMeshes.data[index]);
  65555. }
  65556. engine.setColorWrite(true);
  65557. }
  65558. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65559. renderSubMesh(opaqueSubMeshes.data[index]);
  65560. }
  65561. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65562. renderSubMesh(alphaTestSubMeshes.data[index]);
  65563. }
  65564. if (transparentSubMeshes.length) {
  65565. // Sort sub meshes
  65566. for (index = 0; index < transparentSubMeshes.length; index++) {
  65567. var submesh = transparentSubMeshes.data[index];
  65568. var boundingInfo = submesh.getBoundingInfo();
  65569. if (boundingInfo && scene.activeCamera) {
  65570. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  65571. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  65572. }
  65573. }
  65574. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  65575. sortedArray.sort(function (a, b) {
  65576. // Alpha index first
  65577. if (a._alphaIndex > b._alphaIndex) {
  65578. return 1;
  65579. }
  65580. if (a._alphaIndex < b._alphaIndex) {
  65581. return -1;
  65582. }
  65583. // Then distance to camera
  65584. if (a._distanceToCamera < b._distanceToCamera) {
  65585. return 1;
  65586. }
  65587. if (a._distanceToCamera > b._distanceToCamera) {
  65588. return -1;
  65589. }
  65590. return 0;
  65591. });
  65592. // Render sub meshes
  65593. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65594. for (index = 0; index < sortedArray.length; index++) {
  65595. renderSubMesh(sortedArray[index]);
  65596. }
  65597. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65598. }
  65599. };
  65600. };
  65601. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  65602. var transform = scene.getTransformMatrix();
  65603. var meshPosition;
  65604. if (this.useCustomMeshPosition) {
  65605. meshPosition = this.customMeshPosition;
  65606. }
  65607. else if (this.attachedNode) {
  65608. meshPosition = this.attachedNode.position;
  65609. }
  65610. else {
  65611. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  65612. }
  65613. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  65614. this._screenCoordinates.x = pos.x / this._viewPort.width;
  65615. this._screenCoordinates.y = pos.y / this._viewPort.height;
  65616. if (this.invert)
  65617. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  65618. };
  65619. // Static methods
  65620. /**
  65621. * Creates a default mesh for the Volumeric Light Scattering post-process
  65622. * @param {string} The mesh name
  65623. * @param {BABYLON.Scene} The scene where to create the mesh
  65624. * @return {BABYLON.Mesh} the default mesh
  65625. */
  65626. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  65627. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  65628. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  65629. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  65630. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  65631. mesh.material = material;
  65632. return mesh;
  65633. };
  65634. __decorate([
  65635. BABYLON.serializeAsVector3()
  65636. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  65637. __decorate([
  65638. BABYLON.serialize()
  65639. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  65640. __decorate([
  65641. BABYLON.serialize()
  65642. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  65643. __decorate([
  65644. BABYLON.serializeAsMeshReference()
  65645. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  65646. __decorate([
  65647. BABYLON.serialize()
  65648. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  65649. __decorate([
  65650. BABYLON.serialize()
  65651. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  65652. __decorate([
  65653. BABYLON.serialize()
  65654. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  65655. __decorate([
  65656. BABYLON.serialize()
  65657. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  65658. __decorate([
  65659. BABYLON.serialize()
  65660. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  65661. return VolumetricLightScatteringPostProcess;
  65662. }(BABYLON.PostProcess));
  65663. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  65664. })(BABYLON || (BABYLON = {}));
  65665. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  65666. //
  65667. // This post-process allows the modification of rendered colors by using
  65668. // a 'look-up table' (LUT). This effect is also called Color Grading.
  65669. //
  65670. // The object needs to be provided an url to a texture containing the color
  65671. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  65672. // Use an image editing software to tweak the LUT to match your needs.
  65673. //
  65674. // For an example of a color LUT, see here:
  65675. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  65676. // For explanations on color grading, see here:
  65677. // http://udn.epicgames.com/Three/ColorGrading.html
  65678. //
  65679. var BABYLON;
  65680. (function (BABYLON) {
  65681. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  65682. __extends(ColorCorrectionPostProcess, _super);
  65683. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  65684. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  65685. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65686. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  65687. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65688. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65689. _this.onApply = function (effect) {
  65690. effect.setTexture("colorTable", _this._colorTableTexture);
  65691. };
  65692. return _this;
  65693. }
  65694. return ColorCorrectionPostProcess;
  65695. }(BABYLON.PostProcess));
  65696. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  65697. })(BABYLON || (BABYLON = {}));
  65698. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  65699. var BABYLON;
  65700. (function (BABYLON) {
  65701. var TonemappingOperator;
  65702. (function (TonemappingOperator) {
  65703. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  65704. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  65705. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  65706. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  65707. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  65708. ;
  65709. var TonemapPostProcess = /** @class */ (function (_super) {
  65710. __extends(TonemapPostProcess, _super);
  65711. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  65712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65713. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65714. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  65715. _this._operator = _operator;
  65716. _this.exposureAdjustment = exposureAdjustment;
  65717. var defines = "#define ";
  65718. if (_this._operator === TonemappingOperator.Hable)
  65719. defines += "HABLE_TONEMAPPING";
  65720. else if (_this._operator === TonemappingOperator.Reinhard)
  65721. defines += "REINHARD_TONEMAPPING";
  65722. else if (_this._operator === TonemappingOperator.HejiDawson)
  65723. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  65724. else if (_this._operator === TonemappingOperator.Photographic)
  65725. defines += "PHOTOGRAPHIC_TONEMAPPING";
  65726. //sadly a second call to create the effect.
  65727. _this.updateEffect(defines);
  65728. _this.onApply = function (effect) {
  65729. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  65730. };
  65731. return _this;
  65732. }
  65733. return TonemapPostProcess;
  65734. }(BABYLON.PostProcess));
  65735. BABYLON.TonemapPostProcess = TonemapPostProcess;
  65736. })(BABYLON || (BABYLON = {}));
  65737. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  65738. var BABYLON;
  65739. (function (BABYLON) {
  65740. var DisplayPassPostProcess = /** @class */ (function (_super) {
  65741. __extends(DisplayPassPostProcess, _super);
  65742. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  65743. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  65744. }
  65745. return DisplayPassPostProcess;
  65746. }(BABYLON.PostProcess));
  65747. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  65748. })(BABYLON || (BABYLON = {}));
  65749. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  65750. var BABYLON;
  65751. (function (BABYLON) {
  65752. var HighlightsPostProcess = /** @class */ (function (_super) {
  65753. __extends(HighlightsPostProcess, _super);
  65754. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65755. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65756. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65757. }
  65758. return HighlightsPostProcess;
  65759. }(BABYLON.PostProcess));
  65760. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  65761. })(BABYLON || (BABYLON = {}));
  65762. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  65763. var BABYLON;
  65764. (function (BABYLON) {
  65765. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  65766. __extends(ImageProcessingPostProcess, _super);
  65767. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  65768. if (camera === void 0) { camera = null; }
  65769. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65770. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  65771. _this._fromLinearSpace = true;
  65772. /**
  65773. * Defines cache preventing GC.
  65774. */
  65775. _this._defines = {
  65776. IMAGEPROCESSING: false,
  65777. VIGNETTE: false,
  65778. VIGNETTEBLENDMODEMULTIPLY: false,
  65779. VIGNETTEBLENDMODEOPAQUE: false,
  65780. TONEMAPPING: false,
  65781. CONTRAST: false,
  65782. COLORCURVES: false,
  65783. COLORGRADING: false,
  65784. COLORGRADING3D: false,
  65785. FROMLINEARSPACE: false,
  65786. SAMPLER3DGREENDEPTH: false,
  65787. SAMPLER3DBGRMAP: false,
  65788. IMAGEPROCESSINGPOSTPROCESS: false,
  65789. EXPOSURE: false,
  65790. };
  65791. // Setup the configuration as forced by the constructor. This would then not force the
  65792. // scene materials output in linear space and let untouched the default forward pass.
  65793. if (imageProcessingConfiguration) {
  65794. imageProcessingConfiguration.applyByPostProcess = true;
  65795. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  65796. // This will cause the shader to be compiled
  65797. _this.fromLinearSpace = false;
  65798. }
  65799. else {
  65800. _this._attachImageProcessingConfiguration(null, true);
  65801. _this.imageProcessingConfiguration.applyByPostProcess = true;
  65802. }
  65803. _this.onApply = function (effect) {
  65804. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  65805. };
  65806. return _this;
  65807. }
  65808. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  65809. /**
  65810. * Gets the image processing configuration used either in this material.
  65811. */
  65812. get: function () {
  65813. return this._imageProcessingConfiguration;
  65814. },
  65815. /**
  65816. * Sets the Default image processing configuration used either in the this material.
  65817. *
  65818. * If sets to null, the scene one is in use.
  65819. */
  65820. set: function (value) {
  65821. this._attachImageProcessingConfiguration(value);
  65822. },
  65823. enumerable: true,
  65824. configurable: true
  65825. });
  65826. /**
  65827. * Attaches a new image processing configuration to the PBR Material.
  65828. * @param configuration
  65829. */
  65830. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  65831. var _this = this;
  65832. if (doNotBuild === void 0) { doNotBuild = false; }
  65833. if (configuration === this._imageProcessingConfiguration) {
  65834. return;
  65835. }
  65836. // Detaches observer.
  65837. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65838. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65839. }
  65840. // Pick the scene configuration if needed.
  65841. if (!configuration) {
  65842. var scene = null;
  65843. var engine = this.getEngine();
  65844. var camera = this.getCamera();
  65845. if (camera) {
  65846. scene = camera.getScene();
  65847. }
  65848. else if (engine && engine.scenes) {
  65849. var scenes = engine.scenes;
  65850. scene = scenes[scenes.length - 1];
  65851. }
  65852. else {
  65853. scene = BABYLON.Engine.LastCreatedScene;
  65854. }
  65855. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  65856. }
  65857. else {
  65858. this._imageProcessingConfiguration = configuration;
  65859. }
  65860. // Attaches observer.
  65861. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  65862. _this._updateParameters();
  65863. });
  65864. // Ensure the effect will be rebuilt.
  65865. if (!doNotBuild) {
  65866. this._updateParameters();
  65867. }
  65868. };
  65869. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  65870. /**
  65871. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65872. */
  65873. get: function () {
  65874. return this.imageProcessingConfiguration.colorCurves;
  65875. },
  65876. /**
  65877. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65878. */
  65879. set: function (value) {
  65880. this.imageProcessingConfiguration.colorCurves = value;
  65881. },
  65882. enumerable: true,
  65883. configurable: true
  65884. });
  65885. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  65886. /**
  65887. * Gets wether the color curves effect is enabled.
  65888. */
  65889. get: function () {
  65890. return this.imageProcessingConfiguration.colorCurvesEnabled;
  65891. },
  65892. /**
  65893. * Sets wether the color curves effect is enabled.
  65894. */
  65895. set: function (value) {
  65896. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  65897. },
  65898. enumerable: true,
  65899. configurable: true
  65900. });
  65901. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  65902. /**
  65903. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65904. */
  65905. get: function () {
  65906. return this.imageProcessingConfiguration.colorGradingTexture;
  65907. },
  65908. /**
  65909. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65910. */
  65911. set: function (value) {
  65912. this.imageProcessingConfiguration.colorGradingTexture = value;
  65913. },
  65914. enumerable: true,
  65915. configurable: true
  65916. });
  65917. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  65918. /**
  65919. * Gets wether the color grading effect is enabled.
  65920. */
  65921. get: function () {
  65922. return this.imageProcessingConfiguration.colorGradingEnabled;
  65923. },
  65924. /**
  65925. * Gets wether the color grading effect is enabled.
  65926. */
  65927. set: function (value) {
  65928. this.imageProcessingConfiguration.colorGradingEnabled = value;
  65929. },
  65930. enumerable: true,
  65931. configurable: true
  65932. });
  65933. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  65934. /**
  65935. * Gets exposure used in the effect.
  65936. */
  65937. get: function () {
  65938. return this.imageProcessingConfiguration.exposure;
  65939. },
  65940. /**
  65941. * Sets exposure used in the effect.
  65942. */
  65943. set: function (value) {
  65944. this.imageProcessingConfiguration.exposure = value;
  65945. },
  65946. enumerable: true,
  65947. configurable: true
  65948. });
  65949. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  65950. /**
  65951. * Gets wether tonemapping is enabled or not.
  65952. */
  65953. get: function () {
  65954. return this._imageProcessingConfiguration.toneMappingEnabled;
  65955. },
  65956. /**
  65957. * Sets wether tonemapping is enabled or not
  65958. */
  65959. set: function (value) {
  65960. this._imageProcessingConfiguration.toneMappingEnabled = value;
  65961. },
  65962. enumerable: true,
  65963. configurable: true
  65964. });
  65965. ;
  65966. ;
  65967. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  65968. /**
  65969. * Gets contrast used in the effect.
  65970. */
  65971. get: function () {
  65972. return this.imageProcessingConfiguration.contrast;
  65973. },
  65974. /**
  65975. * Sets contrast used in the effect.
  65976. */
  65977. set: function (value) {
  65978. this.imageProcessingConfiguration.contrast = value;
  65979. },
  65980. enumerable: true,
  65981. configurable: true
  65982. });
  65983. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  65984. /**
  65985. * Gets Vignette stretch size.
  65986. */
  65987. get: function () {
  65988. return this.imageProcessingConfiguration.vignetteStretch;
  65989. },
  65990. /**
  65991. * Sets Vignette stretch size.
  65992. */
  65993. set: function (value) {
  65994. this.imageProcessingConfiguration.vignetteStretch = value;
  65995. },
  65996. enumerable: true,
  65997. configurable: true
  65998. });
  65999. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  66000. /**
  66001. * Gets Vignette centre X Offset.
  66002. */
  66003. get: function () {
  66004. return this.imageProcessingConfiguration.vignetteCentreX;
  66005. },
  66006. /**
  66007. * Sets Vignette centre X Offset.
  66008. */
  66009. set: function (value) {
  66010. this.imageProcessingConfiguration.vignetteCentreX = value;
  66011. },
  66012. enumerable: true,
  66013. configurable: true
  66014. });
  66015. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  66016. /**
  66017. * Gets Vignette centre Y Offset.
  66018. */
  66019. get: function () {
  66020. return this.imageProcessingConfiguration.vignetteCentreY;
  66021. },
  66022. /**
  66023. * Sets Vignette centre Y Offset.
  66024. */
  66025. set: function (value) {
  66026. this.imageProcessingConfiguration.vignetteCentreY = value;
  66027. },
  66028. enumerable: true,
  66029. configurable: true
  66030. });
  66031. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  66032. /**
  66033. * Gets Vignette weight or intensity of the vignette effect.
  66034. */
  66035. get: function () {
  66036. return this.imageProcessingConfiguration.vignetteWeight;
  66037. },
  66038. /**
  66039. * Sets Vignette weight or intensity of the vignette effect.
  66040. */
  66041. set: function (value) {
  66042. this.imageProcessingConfiguration.vignetteWeight = value;
  66043. },
  66044. enumerable: true,
  66045. configurable: true
  66046. });
  66047. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  66048. /**
  66049. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66050. * if vignetteEnabled is set to true.
  66051. */
  66052. get: function () {
  66053. return this.imageProcessingConfiguration.vignetteColor;
  66054. },
  66055. /**
  66056. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66057. * if vignetteEnabled is set to true.
  66058. */
  66059. set: function (value) {
  66060. this.imageProcessingConfiguration.vignetteColor = value;
  66061. },
  66062. enumerable: true,
  66063. configurable: true
  66064. });
  66065. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  66066. /**
  66067. * Gets Camera field of view used by the Vignette effect.
  66068. */
  66069. get: function () {
  66070. return this.imageProcessingConfiguration.vignetteCameraFov;
  66071. },
  66072. /**
  66073. * Sets Camera field of view used by the Vignette effect.
  66074. */
  66075. set: function (value) {
  66076. this.imageProcessingConfiguration.vignetteCameraFov = value;
  66077. },
  66078. enumerable: true,
  66079. configurable: true
  66080. });
  66081. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  66082. /**
  66083. * Gets the vignette blend mode allowing different kind of effect.
  66084. */
  66085. get: function () {
  66086. return this.imageProcessingConfiguration.vignetteBlendMode;
  66087. },
  66088. /**
  66089. * Sets the vignette blend mode allowing different kind of effect.
  66090. */
  66091. set: function (value) {
  66092. this.imageProcessingConfiguration.vignetteBlendMode = value;
  66093. },
  66094. enumerable: true,
  66095. configurable: true
  66096. });
  66097. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  66098. /**
  66099. * Gets wether the vignette effect is enabled.
  66100. */
  66101. get: function () {
  66102. return this.imageProcessingConfiguration.vignetteEnabled;
  66103. },
  66104. /**
  66105. * Sets wether the vignette effect is enabled.
  66106. */
  66107. set: function (value) {
  66108. this.imageProcessingConfiguration.vignetteEnabled = value;
  66109. },
  66110. enumerable: true,
  66111. configurable: true
  66112. });
  66113. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  66114. /**
  66115. * Gets wether the input of the processing is in Gamma or Linear Space.
  66116. */
  66117. get: function () {
  66118. return this._fromLinearSpace;
  66119. },
  66120. /**
  66121. * Sets wether the input of the processing is in Gamma or Linear Space.
  66122. */
  66123. set: function (value) {
  66124. if (this._fromLinearSpace === value) {
  66125. return;
  66126. }
  66127. this._fromLinearSpace = value;
  66128. this._updateParameters();
  66129. },
  66130. enumerable: true,
  66131. configurable: true
  66132. });
  66133. ImageProcessingPostProcess.prototype.getClassName = function () {
  66134. return "ImageProcessingPostProcess";
  66135. };
  66136. ImageProcessingPostProcess.prototype._updateParameters = function () {
  66137. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  66138. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  66139. var defines = "";
  66140. for (var define in this._defines) {
  66141. if (this._defines[define]) {
  66142. defines += "#define " + define + ";\r\n";
  66143. }
  66144. }
  66145. var samplers = ["textureSampler"];
  66146. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  66147. var uniforms = ["scale"];
  66148. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  66149. this.updateEffect(defines, uniforms, samplers);
  66150. };
  66151. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  66152. _super.prototype.dispose.call(this, camera);
  66153. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  66154. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  66155. }
  66156. this.imageProcessingConfiguration.applyByPostProcess = false;
  66157. };
  66158. __decorate([
  66159. BABYLON.serialize()
  66160. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  66161. return ImageProcessingPostProcess;
  66162. }(BABYLON.PostProcess));
  66163. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  66164. })(BABYLON || (BABYLON = {}));
  66165. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  66166. var BABYLON;
  66167. (function (BABYLON) {
  66168. var BlurPostProcess = /** @class */ (function (_super) {
  66169. __extends(BlurPostProcess, _super);
  66170. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  66171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66172. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66173. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  66174. _this.direction = direction;
  66175. _this._packedFloat = false;
  66176. _this._staticDefines = "";
  66177. _this.onApplyObservable.add(function (effect) {
  66178. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  66179. });
  66180. _this.kernel = kernel;
  66181. return _this;
  66182. }
  66183. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  66184. /**
  66185. * Gets the length in pixels of the blur sample region
  66186. */
  66187. get: function () {
  66188. return this._idealKernel;
  66189. },
  66190. /**
  66191. * Sets the length in pixels of the blur sample region
  66192. */
  66193. set: function (v) {
  66194. if (this._idealKernel === v) {
  66195. return;
  66196. }
  66197. v = Math.max(v, 1);
  66198. this._idealKernel = v;
  66199. this._kernel = this._nearestBestKernel(v);
  66200. this._updateParameters();
  66201. },
  66202. enumerable: true,
  66203. configurable: true
  66204. });
  66205. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  66206. /**
  66207. * Gets wether or not the blur is unpacking/repacking floats
  66208. */
  66209. get: function () {
  66210. return this._packedFloat;
  66211. },
  66212. /**
  66213. * Sets wether or not the blur needs to unpack/repack floats
  66214. */
  66215. set: function (v) {
  66216. if (this._packedFloat === v) {
  66217. return;
  66218. }
  66219. this._packedFloat = v;
  66220. this._updateParameters();
  66221. },
  66222. enumerable: true,
  66223. configurable: true
  66224. });
  66225. BlurPostProcess.prototype._updateParameters = function () {
  66226. // Generate sampling offsets and weights
  66227. var N = this._kernel;
  66228. var centerIndex = (N - 1) / 2;
  66229. // Generate Gaussian sampling weights over kernel
  66230. var offsets = [];
  66231. var weights = [];
  66232. var totalWeight = 0;
  66233. for (var i = 0; i < N; i++) {
  66234. var u = i / (N - 1);
  66235. var w = this._gaussianWeight(u * 2.0 - 1);
  66236. offsets[i] = (i - centerIndex);
  66237. weights[i] = w;
  66238. totalWeight += w;
  66239. }
  66240. // Normalize weights
  66241. for (var i = 0; i < weights.length; i++) {
  66242. weights[i] /= totalWeight;
  66243. }
  66244. // Optimize: combine samples to take advantage of hardware linear sampling
  66245. // Walk from left to center, combining pairs (symmetrically)
  66246. var linearSamplingWeights = [];
  66247. var linearSamplingOffsets = [];
  66248. var linearSamplingMap = [];
  66249. for (var i = 0; i <= centerIndex; i += 2) {
  66250. var j = Math.min(i + 1, Math.floor(centerIndex));
  66251. var singleCenterSample = i === j;
  66252. if (singleCenterSample) {
  66253. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66254. }
  66255. else {
  66256. var sharedCell = j === centerIndex;
  66257. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  66258. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  66259. if (offsetLinear === 0) {
  66260. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66261. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  66262. }
  66263. else {
  66264. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  66265. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  66266. }
  66267. }
  66268. }
  66269. for (var i = 0; i < linearSamplingMap.length; i++) {
  66270. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  66271. linearSamplingWeights[i] = linearSamplingMap[i].w;
  66272. }
  66273. // Replace with optimized
  66274. offsets = linearSamplingOffsets;
  66275. weights = linearSamplingWeights;
  66276. // Generate shaders
  66277. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  66278. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  66279. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  66280. var defines = "";
  66281. defines += this._staticDefines;
  66282. for (var i = 0; i < varyingCount; i++) {
  66283. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  66284. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  66285. }
  66286. var depCount = 0;
  66287. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  66288. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  66289. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  66290. depCount++;
  66291. }
  66292. if (this.packedFloat) {
  66293. defines += "#define PACKEDFLOAT 1";
  66294. }
  66295. this.updateEffect(defines, null, null, {
  66296. varyingCount: varyingCount,
  66297. depCount: depCount
  66298. });
  66299. };
  66300. /**
  66301. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  66302. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  66303. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  66304. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  66305. * The gaps between physical kernels are compensated for in the weighting of the samples
  66306. * @param idealKernel Ideal blur kernel.
  66307. * @return Nearest best kernel.
  66308. */
  66309. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  66310. var v = Math.round(idealKernel);
  66311. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  66312. var k = _a[_i];
  66313. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  66314. return Math.max(k, 3);
  66315. }
  66316. }
  66317. return Math.max(v, 3);
  66318. };
  66319. /**
  66320. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  66321. * @param x The point on the Gaussian distribution to sample.
  66322. * @return the value of the Gaussian function at x.
  66323. */
  66324. BlurPostProcess.prototype._gaussianWeight = function (x) {
  66325. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  66326. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  66327. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  66328. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  66329. // truncated at around 1.3% of peak strength.
  66330. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  66331. var sigma = (1 / 3);
  66332. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  66333. var exponent = -((x * x) / (2.0 * sigma * sigma));
  66334. var weight = (1.0 / denominator) * Math.exp(exponent);
  66335. return weight;
  66336. };
  66337. /**
  66338. * Generates a string that can be used as a floating point number in GLSL.
  66339. * @param x Value to print.
  66340. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  66341. * @return GLSL float string.
  66342. */
  66343. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  66344. if (decimalFigures === void 0) { decimalFigures = 8; }
  66345. return x.toFixed(decimalFigures).replace(/0+$/, '');
  66346. };
  66347. return BlurPostProcess;
  66348. }(BABYLON.PostProcess));
  66349. BABYLON.BlurPostProcess = BlurPostProcess;
  66350. })(BABYLON || (BABYLON = {}));
  66351. //# sourceMappingURL=babylon.blurPostProcess.js.map
  66352. var BABYLON;
  66353. (function (BABYLON) {
  66354. /**
  66355. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  66356. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  66357. * based on samples that have a large difference in distance than the center pixel.
  66358. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66359. */
  66360. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  66361. __extends(DepthOfFieldBlurPostProcess, _super);
  66362. /**
  66363. * Creates a new instance of @see CircleOfConfusionPostProcess
  66364. * @param name The name of the effect.
  66365. * @param scene The scene the effect belongs to.
  66366. * @param direction The direction the blur should be applied.
  66367. * @param kernel The size of the kernel used to blur.
  66368. * @param options The required width/height ratio to downsize to before computing the render pass.
  66369. * @param camera The camera to apply the render pass to.
  66370. * @param depthMap The depth map to be used to avoid blurring accross edges
  66371. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  66372. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66373. * @param engine The engine which the post process will be applied. (default: current engine)
  66374. * @param reusable If the post process can be reused on the same frame. (default: false)
  66375. * @param textureType Type of textures used when performing the post process. (default: 0)
  66376. */
  66377. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, depthMap, imageToBlur, samplingMode, engine, reusable, textureType) {
  66378. if (imageToBlur === void 0) { imageToBlur = null; }
  66379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66380. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66381. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) || this;
  66382. _this.direction = direction;
  66383. _this._staticDefines += "#define DOF 1\r\n";
  66384. _this.onApplyObservable.add(function (effect) {
  66385. // TODO: setTextureFromPostProcess seems to be setting the input texture instead of output of the post process passed in
  66386. if (imageToBlur != null) {
  66387. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  66388. }
  66389. effect.setTexture("depthSampler", depthMap);
  66390. if (scene.activeCamera) {
  66391. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66392. }
  66393. });
  66394. return _this;
  66395. }
  66396. return DepthOfFieldBlurPostProcess;
  66397. }(BABYLON.BlurPostProcess));
  66398. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  66399. })(BABYLON || (BABYLON = {}));
  66400. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  66401. var BABYLON;
  66402. (function (BABYLON) {
  66403. var Bone = /** @class */ (function (_super) {
  66404. __extends(Bone, _super);
  66405. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  66406. if (parentBone === void 0) { parentBone = null; }
  66407. if (localMatrix === void 0) { localMatrix = null; }
  66408. if (restPose === void 0) { restPose = null; }
  66409. if (baseMatrix === void 0) { baseMatrix = null; }
  66410. if (index === void 0) { index = null; }
  66411. var _this = _super.call(this, name, skeleton.getScene()) || this;
  66412. _this.name = name;
  66413. _this.children = new Array();
  66414. _this.animations = new Array();
  66415. // Set this value to map this bone to a different index in the transform matrices.
  66416. // Set this value to -1 to exclude the bone from the transform matrices.
  66417. _this._index = null;
  66418. _this._worldTransform = new BABYLON.Matrix();
  66419. _this._absoluteTransform = new BABYLON.Matrix();
  66420. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  66421. _this._scaleMatrix = BABYLON.Matrix.Identity();
  66422. _this._scaleVector = BABYLON.Vector3.One();
  66423. _this._negateScaleChildren = BABYLON.Vector3.One();
  66424. _this._scalingDeterminant = 1;
  66425. _this._skeleton = skeleton;
  66426. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  66427. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  66428. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  66429. _this._index = index;
  66430. skeleton.bones.push(_this);
  66431. _this.setParent(parentBone, false);
  66432. _this._updateDifferenceMatrix();
  66433. return _this;
  66434. }
  66435. Object.defineProperty(Bone.prototype, "_matrix", {
  66436. get: function () {
  66437. return this._localMatrix;
  66438. },
  66439. set: function (val) {
  66440. if (this._localMatrix) {
  66441. this._localMatrix.copyFrom(val);
  66442. }
  66443. else {
  66444. this._localMatrix = val;
  66445. }
  66446. },
  66447. enumerable: true,
  66448. configurable: true
  66449. });
  66450. // Members
  66451. Bone.prototype.getSkeleton = function () {
  66452. return this._skeleton;
  66453. };
  66454. Bone.prototype.getParent = function () {
  66455. return this._parent;
  66456. };
  66457. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  66458. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66459. if (this._parent === parent) {
  66460. return;
  66461. }
  66462. if (this._parent) {
  66463. var index = this._parent.children.indexOf(this);
  66464. if (index !== -1) {
  66465. this._parent.children.splice(index, 1);
  66466. }
  66467. }
  66468. this._parent = parent;
  66469. if (this._parent) {
  66470. this._parent.children.push(this);
  66471. }
  66472. if (updateDifferenceMatrix) {
  66473. this._updateDifferenceMatrix();
  66474. }
  66475. };
  66476. Bone.prototype.getLocalMatrix = function () {
  66477. return this._localMatrix;
  66478. };
  66479. Bone.prototype.getBaseMatrix = function () {
  66480. return this._baseMatrix;
  66481. };
  66482. Bone.prototype.getRestPose = function () {
  66483. return this._restPose;
  66484. };
  66485. Bone.prototype.returnToRest = function () {
  66486. this.updateMatrix(this._restPose.clone());
  66487. };
  66488. Bone.prototype.getWorldMatrix = function () {
  66489. return this._worldTransform;
  66490. };
  66491. Bone.prototype.getInvertedAbsoluteTransform = function () {
  66492. return this._invertedAbsoluteTransform;
  66493. };
  66494. Bone.prototype.getAbsoluteTransform = function () {
  66495. return this._absoluteTransform;
  66496. };
  66497. Object.defineProperty(Bone.prototype, "position", {
  66498. // Properties (matches AbstractMesh properties)
  66499. get: function () {
  66500. return this.getPosition();
  66501. },
  66502. set: function (newPosition) {
  66503. this.setPosition(newPosition);
  66504. },
  66505. enumerable: true,
  66506. configurable: true
  66507. });
  66508. Object.defineProperty(Bone.prototype, "rotation", {
  66509. get: function () {
  66510. return this.getRotation();
  66511. },
  66512. set: function (newRotation) {
  66513. this.setRotation(newRotation);
  66514. },
  66515. enumerable: true,
  66516. configurable: true
  66517. });
  66518. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  66519. get: function () {
  66520. return this.getRotationQuaternion();
  66521. },
  66522. set: function (newRotation) {
  66523. this.setRotationQuaternion(newRotation);
  66524. },
  66525. enumerable: true,
  66526. configurable: true
  66527. });
  66528. Object.defineProperty(Bone.prototype, "scaling", {
  66529. get: function () {
  66530. return this.getScale();
  66531. },
  66532. set: function (newScaling) {
  66533. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  66534. },
  66535. enumerable: true,
  66536. configurable: true
  66537. });
  66538. // Methods
  66539. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  66540. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66541. this._baseMatrix = matrix.clone();
  66542. this._localMatrix = matrix.clone();
  66543. this._skeleton._markAsDirty();
  66544. if (updateDifferenceMatrix) {
  66545. this._updateDifferenceMatrix();
  66546. }
  66547. };
  66548. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  66549. if (!rootMatrix) {
  66550. rootMatrix = this._baseMatrix;
  66551. }
  66552. if (this._parent) {
  66553. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66554. }
  66555. else {
  66556. this._absoluteTransform.copyFrom(rootMatrix);
  66557. }
  66558. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  66559. for (var index = 0; index < this.children.length; index++) {
  66560. this.children[index]._updateDifferenceMatrix();
  66561. }
  66562. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  66563. };
  66564. Bone.prototype.markAsDirty = function () {
  66565. this._currentRenderId++;
  66566. this._skeleton._markAsDirty();
  66567. };
  66568. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  66569. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66570. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  66571. // all animation may be coming from a library skeleton, so may need to create animation
  66572. if (this.animations.length === 0) {
  66573. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  66574. this.animations[0].setKeys([]);
  66575. }
  66576. // get animation info / verify there is such a range from the source bone
  66577. var sourceRange = source.animations[0].getRange(rangeName);
  66578. if (!sourceRange) {
  66579. return false;
  66580. }
  66581. var from = sourceRange.from;
  66582. var to = sourceRange.to;
  66583. var sourceKeys = source.animations[0].getKeys();
  66584. // rescaling prep
  66585. var sourceBoneLength = source.length;
  66586. var sourceParent = source.getParent();
  66587. var parent = this.getParent();
  66588. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  66589. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  66590. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  66591. var destKeys = this.animations[0].getKeys();
  66592. // loop vars declaration
  66593. var orig;
  66594. var origTranslation;
  66595. var mat;
  66596. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  66597. orig = sourceKeys[key];
  66598. if (orig.frame >= from && orig.frame <= to) {
  66599. if (rescaleAsRequired) {
  66600. mat = orig.value.clone();
  66601. // scale based on parent ratio, when bone has parent
  66602. if (parentScalingReqd) {
  66603. origTranslation = mat.getTranslation();
  66604. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  66605. // scale based on skeleton dimension ratio when root bone, and value is passed
  66606. }
  66607. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  66608. origTranslation = mat.getTranslation();
  66609. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  66610. // use original when root bone, and no data for skelDimensionsRatio
  66611. }
  66612. else {
  66613. mat = orig.value;
  66614. }
  66615. }
  66616. else {
  66617. mat = orig.value;
  66618. }
  66619. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  66620. }
  66621. }
  66622. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  66623. return true;
  66624. };
  66625. /**
  66626. * Translate the bone in local or world space.
  66627. * @param vec The amount to translate the bone.
  66628. * @param space The space that the translation is in.
  66629. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66630. */
  66631. Bone.prototype.translate = function (vec, space, mesh) {
  66632. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66633. var lm = this.getLocalMatrix();
  66634. if (space == BABYLON.Space.LOCAL) {
  66635. lm.m[12] += vec.x;
  66636. lm.m[13] += vec.y;
  66637. lm.m[14] += vec.z;
  66638. }
  66639. else {
  66640. var wm = null;
  66641. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66642. if (mesh) {
  66643. wm = mesh.getWorldMatrix();
  66644. }
  66645. this._skeleton.computeAbsoluteTransforms();
  66646. var tmat = Bone._tmpMats[0];
  66647. var tvec = Bone._tmpVecs[0];
  66648. if (this._parent) {
  66649. if (mesh && wm) {
  66650. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66651. tmat.multiplyToRef(wm, tmat);
  66652. }
  66653. else {
  66654. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66655. }
  66656. }
  66657. tmat.m[12] = 0;
  66658. tmat.m[13] = 0;
  66659. tmat.m[14] = 0;
  66660. tmat.invert();
  66661. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  66662. lm.m[12] += tvec.x;
  66663. lm.m[13] += tvec.y;
  66664. lm.m[14] += tvec.z;
  66665. }
  66666. this.markAsDirty();
  66667. };
  66668. /**
  66669. * Set the postion of the bone in local or world space.
  66670. * @param position The position to set the bone.
  66671. * @param space The space that the position is in.
  66672. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66673. */
  66674. Bone.prototype.setPosition = function (position, space, mesh) {
  66675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66676. var lm = this.getLocalMatrix();
  66677. if (space == BABYLON.Space.LOCAL) {
  66678. lm.m[12] = position.x;
  66679. lm.m[13] = position.y;
  66680. lm.m[14] = position.z;
  66681. }
  66682. else {
  66683. var wm = null;
  66684. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66685. if (mesh) {
  66686. wm = mesh.getWorldMatrix();
  66687. }
  66688. this._skeleton.computeAbsoluteTransforms();
  66689. var tmat = Bone._tmpMats[0];
  66690. var vec = Bone._tmpVecs[0];
  66691. if (this._parent) {
  66692. if (mesh && wm) {
  66693. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66694. tmat.multiplyToRef(wm, tmat);
  66695. }
  66696. else {
  66697. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66698. }
  66699. }
  66700. tmat.invert();
  66701. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  66702. lm.m[12] = vec.x;
  66703. lm.m[13] = vec.y;
  66704. lm.m[14] = vec.z;
  66705. }
  66706. this.markAsDirty();
  66707. };
  66708. /**
  66709. * Set the absolute postion of the bone (world space).
  66710. * @param position The position to set the bone.
  66711. * @param mesh The mesh that this bone is attached to.
  66712. */
  66713. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  66714. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  66715. };
  66716. /**
  66717. * Set the scale of the bone on the x, y and z axes.
  66718. * @param x The scale of the bone on the x axis.
  66719. * @param x The scale of the bone on the y axis.
  66720. * @param z The scale of the bone on the z axis.
  66721. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66722. */
  66723. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  66724. if (scaleChildren === void 0) { scaleChildren = false; }
  66725. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  66726. if (!scaleChildren) {
  66727. this._negateScaleChildren.x = 1 / x;
  66728. this._negateScaleChildren.y = 1 / y;
  66729. this._negateScaleChildren.z = 1 / z;
  66730. }
  66731. this._syncScaleVector();
  66732. }
  66733. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  66734. };
  66735. /**
  66736. * Scale the bone on the x, y and z axes.
  66737. * @param x The amount to scale the bone on the x axis.
  66738. * @param x The amount to scale the bone on the y axis.
  66739. * @param z The amount to scale the bone on the z axis.
  66740. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66741. */
  66742. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  66743. if (scaleChildren === void 0) { scaleChildren = false; }
  66744. var locMat = this.getLocalMatrix();
  66745. var origLocMat = Bone._tmpMats[0];
  66746. origLocMat.copyFrom(locMat);
  66747. var origLocMatInv = Bone._tmpMats[1];
  66748. origLocMatInv.copyFrom(origLocMat);
  66749. origLocMatInv.invert();
  66750. var scaleMat = Bone._tmpMats[2];
  66751. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  66752. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  66753. this._scaleVector.x *= x;
  66754. this._scaleVector.y *= y;
  66755. this._scaleVector.z *= z;
  66756. locMat.multiplyToRef(origLocMatInv, locMat);
  66757. locMat.multiplyToRef(scaleMat, locMat);
  66758. locMat.multiplyToRef(origLocMat, locMat);
  66759. var parent = this.getParent();
  66760. if (parent) {
  66761. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  66762. }
  66763. else {
  66764. this.getAbsoluteTransform().copyFrom(locMat);
  66765. }
  66766. var len = this.children.length;
  66767. scaleMat.invert();
  66768. for (var i = 0; i < len; i++) {
  66769. var child = this.children[i];
  66770. var cm = child.getLocalMatrix();
  66771. cm.multiplyToRef(scaleMat, cm);
  66772. var lm = child.getLocalMatrix();
  66773. lm.m[12] *= x;
  66774. lm.m[13] *= y;
  66775. lm.m[14] *= z;
  66776. }
  66777. this.computeAbsoluteTransforms();
  66778. if (scaleChildren) {
  66779. for (var i = 0; i < len; i++) {
  66780. this.children[i].scale(x, y, z, scaleChildren);
  66781. }
  66782. }
  66783. this.markAsDirty();
  66784. };
  66785. /**
  66786. * Set the yaw, pitch, and roll of the bone in local or world space.
  66787. * @param yaw The rotation of the bone on the y axis.
  66788. * @param pitch The rotation of the bone on the x axis.
  66789. * @param roll The rotation of the bone on the z axis.
  66790. * @param space The space that the axes of rotation are in.
  66791. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66792. */
  66793. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  66794. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66795. var rotMat = Bone._tmpMats[0];
  66796. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  66797. var rotMatInv = Bone._tmpMats[1];
  66798. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66799. rotMatInv.multiplyToRef(rotMat, rotMat);
  66800. this._rotateWithMatrix(rotMat, space, mesh);
  66801. };
  66802. /**
  66803. * Rotate the bone on an axis in local or world space.
  66804. * @param axis The axis to rotate the bone on.
  66805. * @param amount The amount to rotate the bone.
  66806. * @param space The space that the axis is in.
  66807. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66808. */
  66809. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  66810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66811. var rmat = Bone._tmpMats[0];
  66812. rmat.m[12] = 0;
  66813. rmat.m[13] = 0;
  66814. rmat.m[14] = 0;
  66815. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  66816. this._rotateWithMatrix(rmat, space, mesh);
  66817. };
  66818. /**
  66819. * Set the rotation of the bone to a particular axis angle in local or world space.
  66820. * @param axis The axis to rotate the bone on.
  66821. * @param angle The angle that the bone should be rotated to.
  66822. * @param space The space that the axis is in.
  66823. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66824. */
  66825. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  66826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66827. var rotMat = Bone._tmpMats[0];
  66828. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  66829. var rotMatInv = Bone._tmpMats[1];
  66830. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66831. rotMatInv.multiplyToRef(rotMat, rotMat);
  66832. this._rotateWithMatrix(rotMat, space, mesh);
  66833. };
  66834. /**
  66835. * Set the euler rotation of the bone in local of world space.
  66836. * @param rotation The euler rotation that the bone should be set to.
  66837. * @param space The space that the rotation is in.
  66838. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66839. */
  66840. Bone.prototype.setRotation = function (rotation, space, mesh) {
  66841. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66842. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  66843. };
  66844. /**
  66845. * Set the quaternion rotation of the bone in local of world space.
  66846. * @param quat The quaternion rotation that the bone should be set to.
  66847. * @param space The space that the rotation is in.
  66848. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66849. */
  66850. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  66851. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66852. var rotMatInv = Bone._tmpMats[0];
  66853. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66854. var rotMat = Bone._tmpMats[1];
  66855. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  66856. rotMatInv.multiplyToRef(rotMat, rotMat);
  66857. this._rotateWithMatrix(rotMat, space, mesh);
  66858. };
  66859. /**
  66860. * Set the rotation matrix of the bone in local of world space.
  66861. * @param rotMat The rotation matrix that the bone should be set to.
  66862. * @param space The space that the rotation is in.
  66863. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66864. */
  66865. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  66866. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66867. var rotMatInv = Bone._tmpMats[0];
  66868. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66869. var rotMat2 = Bone._tmpMats[1];
  66870. rotMat2.copyFrom(rotMat);
  66871. rotMatInv.multiplyToRef(rotMat, rotMat2);
  66872. this._rotateWithMatrix(rotMat2, space, mesh);
  66873. };
  66874. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  66875. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66876. var lmat = this.getLocalMatrix();
  66877. var lx = lmat.m[12];
  66878. var ly = lmat.m[13];
  66879. var lz = lmat.m[14];
  66880. var parent = this.getParent();
  66881. var parentScale = Bone._tmpMats[3];
  66882. var parentScaleInv = Bone._tmpMats[4];
  66883. if (parent) {
  66884. if (space == BABYLON.Space.WORLD) {
  66885. if (mesh) {
  66886. parentScale.copyFrom(mesh.getWorldMatrix());
  66887. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  66888. }
  66889. else {
  66890. parentScale.copyFrom(parent.getAbsoluteTransform());
  66891. }
  66892. }
  66893. else {
  66894. parentScale = parent._scaleMatrix;
  66895. }
  66896. parentScaleInv.copyFrom(parentScale);
  66897. parentScaleInv.invert();
  66898. lmat.multiplyToRef(parentScale, lmat);
  66899. lmat.multiplyToRef(rmat, lmat);
  66900. lmat.multiplyToRef(parentScaleInv, lmat);
  66901. }
  66902. else {
  66903. if (space == BABYLON.Space.WORLD && mesh) {
  66904. parentScale.copyFrom(mesh.getWorldMatrix());
  66905. parentScaleInv.copyFrom(parentScale);
  66906. parentScaleInv.invert();
  66907. lmat.multiplyToRef(parentScale, lmat);
  66908. lmat.multiplyToRef(rmat, lmat);
  66909. lmat.multiplyToRef(parentScaleInv, lmat);
  66910. }
  66911. else {
  66912. lmat.multiplyToRef(rmat, lmat);
  66913. }
  66914. }
  66915. lmat.m[12] = lx;
  66916. lmat.m[13] = ly;
  66917. lmat.m[14] = lz;
  66918. this.computeAbsoluteTransforms();
  66919. this.markAsDirty();
  66920. };
  66921. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  66922. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66923. if (space == BABYLON.Space.WORLD) {
  66924. var scaleMatrix = Bone._tmpMats[2];
  66925. scaleMatrix.copyFrom(this._scaleMatrix);
  66926. rotMatInv.copyFrom(this.getAbsoluteTransform());
  66927. if (mesh) {
  66928. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  66929. var meshScale = Bone._tmpMats[3];
  66930. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  66931. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  66932. }
  66933. rotMatInv.invert();
  66934. scaleMatrix.m[0] *= this._scalingDeterminant;
  66935. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66936. }
  66937. else {
  66938. rotMatInv.copyFrom(this.getLocalMatrix());
  66939. rotMatInv.invert();
  66940. var scaleMatrix = Bone._tmpMats[2];
  66941. scaleMatrix.copyFrom(this._scaleMatrix);
  66942. if (this._parent) {
  66943. var pscaleMatrix = Bone._tmpMats[3];
  66944. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  66945. pscaleMatrix.invert();
  66946. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  66947. }
  66948. else {
  66949. scaleMatrix.m[0] *= this._scalingDeterminant;
  66950. }
  66951. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66952. }
  66953. };
  66954. /**
  66955. * Get the scale of the bone
  66956. * @returns the scale of the bone
  66957. */
  66958. Bone.prototype.getScale = function () {
  66959. return this._scaleVector.clone();
  66960. };
  66961. /**
  66962. * Copy the scale of the bone to a vector3.
  66963. * @param result The vector3 to copy the scale to
  66964. */
  66965. Bone.prototype.getScaleToRef = function (result) {
  66966. result.copyFrom(this._scaleVector);
  66967. };
  66968. /**
  66969. * Get the position of the bone in local or world space.
  66970. * @param space The space that the returned position is in.
  66971. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66972. * @returns The position of the bone
  66973. */
  66974. Bone.prototype.getPosition = function (space, mesh) {
  66975. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66976. if (mesh === void 0) { mesh = null; }
  66977. var pos = BABYLON.Vector3.Zero();
  66978. this.getPositionToRef(space, mesh, pos);
  66979. return pos;
  66980. };
  66981. /**
  66982. * Copy the position of the bone to a vector3 in local or world space.
  66983. * @param space The space that the returned position is in.
  66984. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66985. * @param result The vector3 to copy the position to.
  66986. */
  66987. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  66988. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66989. if (space == BABYLON.Space.LOCAL) {
  66990. var lm = this.getLocalMatrix();
  66991. result.x = lm.m[12];
  66992. result.y = lm.m[13];
  66993. result.z = lm.m[14];
  66994. }
  66995. else {
  66996. var wm = null;
  66997. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66998. if (mesh) {
  66999. wm = mesh.getWorldMatrix();
  67000. }
  67001. this._skeleton.computeAbsoluteTransforms();
  67002. var tmat = Bone._tmpMats[0];
  67003. if (mesh && wm) {
  67004. tmat.copyFrom(this.getAbsoluteTransform());
  67005. tmat.multiplyToRef(wm, tmat);
  67006. }
  67007. else {
  67008. tmat = this.getAbsoluteTransform();
  67009. }
  67010. result.x = tmat.m[12];
  67011. result.y = tmat.m[13];
  67012. result.z = tmat.m[14];
  67013. }
  67014. };
  67015. /**
  67016. * Get the absolute position of the bone (world space).
  67017. * @param mesh The mesh that this bone is attached to.
  67018. * @returns The absolute position of the bone
  67019. */
  67020. Bone.prototype.getAbsolutePosition = function (mesh) {
  67021. if (mesh === void 0) { mesh = null; }
  67022. var pos = BABYLON.Vector3.Zero();
  67023. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  67024. return pos;
  67025. };
  67026. /**
  67027. * Copy the absolute position of the bone (world space) to the result param.
  67028. * @param mesh The mesh that this bone is attached to.
  67029. * @param result The vector3 to copy the absolute position to.
  67030. */
  67031. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  67032. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  67033. };
  67034. /**
  67035. * Compute the absolute transforms of this bone and its children.
  67036. */
  67037. Bone.prototype.computeAbsoluteTransforms = function () {
  67038. if (this._parent) {
  67039. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  67040. }
  67041. else {
  67042. this._absoluteTransform.copyFrom(this._localMatrix);
  67043. var poseMatrix = this._skeleton.getPoseMatrix();
  67044. if (poseMatrix) {
  67045. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  67046. }
  67047. }
  67048. var children = this.children;
  67049. var len = children.length;
  67050. for (var i = 0; i < len; i++) {
  67051. children[i].computeAbsoluteTransforms();
  67052. }
  67053. };
  67054. Bone.prototype._syncScaleVector = function () {
  67055. var lm = this.getLocalMatrix();
  67056. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  67057. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  67058. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  67059. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  67060. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  67061. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  67062. this._scaleVector.x = xs * Math.sqrt(xsq);
  67063. this._scaleVector.y = ys * Math.sqrt(ysq);
  67064. this._scaleVector.z = zs * Math.sqrt(zsq);
  67065. if (this._parent) {
  67066. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  67067. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  67068. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  67069. }
  67070. 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);
  67071. };
  67072. /**
  67073. * Get the world direction from an axis that is in the local space of the bone.
  67074. * @param localAxis The local direction that is used to compute the world direction.
  67075. * @param mesh The mesh that this bone is attached to.
  67076. * @returns The world direction
  67077. */
  67078. Bone.prototype.getDirection = function (localAxis, mesh) {
  67079. if (mesh === void 0) { mesh = null; }
  67080. var result = BABYLON.Vector3.Zero();
  67081. this.getDirectionToRef(localAxis, mesh, result);
  67082. return result;
  67083. };
  67084. /**
  67085. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  67086. * @param localAxis The local direction that is used to compute the world direction.
  67087. * @param mesh The mesh that this bone is attached to.
  67088. * @param result The vector3 that the world direction will be copied to.
  67089. */
  67090. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  67091. if (mesh === void 0) { mesh = null; }
  67092. var wm = null;
  67093. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67094. if (mesh) {
  67095. wm = mesh.getWorldMatrix();
  67096. }
  67097. this._skeleton.computeAbsoluteTransforms();
  67098. var mat = Bone._tmpMats[0];
  67099. mat.copyFrom(this.getAbsoluteTransform());
  67100. if (mesh && wm) {
  67101. mat.multiplyToRef(wm, mat);
  67102. }
  67103. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  67104. result.normalize();
  67105. };
  67106. /**
  67107. * Get the euler rotation of the bone in local or world space.
  67108. * @param space The space that the rotation should be in.
  67109. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67110. * @returns The euler rotation
  67111. */
  67112. Bone.prototype.getRotation = function (space, mesh) {
  67113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67114. if (mesh === void 0) { mesh = null; }
  67115. var result = BABYLON.Vector3.Zero();
  67116. this.getRotationToRef(space, mesh, result);
  67117. return result;
  67118. };
  67119. /**
  67120. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  67121. * @param space The space that the rotation should be in.
  67122. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67123. * @param result The vector3 that the rotation should be copied to.
  67124. */
  67125. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  67126. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67127. if (mesh === void 0) { mesh = null; }
  67128. var quat = Bone._tmpQuat;
  67129. this.getRotationQuaternionToRef(space, mesh, quat);
  67130. quat.toEulerAnglesToRef(result);
  67131. };
  67132. /**
  67133. * Get the quaternion rotation of the bone in either local or world space.
  67134. * @param space The space that the rotation should be in.
  67135. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67136. * @returns The quaternion rotation
  67137. */
  67138. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  67139. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67140. if (mesh === void 0) { mesh = null; }
  67141. var result = BABYLON.Quaternion.Identity();
  67142. this.getRotationQuaternionToRef(space, mesh, result);
  67143. return result;
  67144. };
  67145. /**
  67146. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  67147. * @param space The space that the rotation should be in.
  67148. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67149. * @param result The quaternion that the rotation should be copied to.
  67150. */
  67151. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  67152. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67153. if (mesh === void 0) { mesh = null; }
  67154. if (space == BABYLON.Space.LOCAL) {
  67155. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67156. }
  67157. else {
  67158. var mat = Bone._tmpMats[0];
  67159. var amat = this.getAbsoluteTransform();
  67160. if (mesh) {
  67161. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67162. }
  67163. else {
  67164. mat.copyFrom(amat);
  67165. }
  67166. mat.m[0] *= this._scalingDeterminant;
  67167. mat.m[1] *= this._scalingDeterminant;
  67168. mat.m[2] *= this._scalingDeterminant;
  67169. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67170. }
  67171. };
  67172. /**
  67173. * Get the rotation matrix of the bone in local or world space.
  67174. * @param space The space that the rotation should be in.
  67175. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67176. * @returns The rotation matrix
  67177. */
  67178. Bone.prototype.getRotationMatrix = function (space, mesh) {
  67179. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67180. var result = BABYLON.Matrix.Identity();
  67181. this.getRotationMatrixToRef(space, mesh, result);
  67182. return result;
  67183. };
  67184. /**
  67185. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  67186. * @param space The space that the rotation should be in.
  67187. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67188. * @param result The quaternion that the rotation should be copied to.
  67189. */
  67190. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  67191. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67192. if (space == BABYLON.Space.LOCAL) {
  67193. this.getLocalMatrix().getRotationMatrixToRef(result);
  67194. }
  67195. else {
  67196. var mat = Bone._tmpMats[0];
  67197. var amat = this.getAbsoluteTransform();
  67198. if (mesh) {
  67199. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67200. }
  67201. else {
  67202. mat.copyFrom(amat);
  67203. }
  67204. mat.m[0] *= this._scalingDeterminant;
  67205. mat.m[1] *= this._scalingDeterminant;
  67206. mat.m[2] *= this._scalingDeterminant;
  67207. mat.getRotationMatrixToRef(result);
  67208. }
  67209. };
  67210. /**
  67211. * Get the world position of a point that is in the local space of the bone.
  67212. * @param position The local position
  67213. * @param mesh The mesh that this bone is attached to.
  67214. * @returns The world position
  67215. */
  67216. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  67217. if (mesh === void 0) { mesh = null; }
  67218. var result = BABYLON.Vector3.Zero();
  67219. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  67220. return result;
  67221. };
  67222. /**
  67223. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  67224. * @param position The local position
  67225. * @param mesh The mesh that this bone is attached to.
  67226. * @param result The vector3 that the world position should be copied to.
  67227. */
  67228. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  67229. if (mesh === void 0) { mesh = null; }
  67230. var wm = null;
  67231. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67232. if (mesh) {
  67233. wm = mesh.getWorldMatrix();
  67234. }
  67235. this._skeleton.computeAbsoluteTransforms();
  67236. var tmat = Bone._tmpMats[0];
  67237. if (mesh && wm) {
  67238. tmat.copyFrom(this.getAbsoluteTransform());
  67239. tmat.multiplyToRef(wm, tmat);
  67240. }
  67241. else {
  67242. tmat = this.getAbsoluteTransform();
  67243. }
  67244. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67245. };
  67246. /**
  67247. * Get the local position of a point that is in world space.
  67248. * @param position The world position
  67249. * @param mesh The mesh that this bone is attached to.
  67250. * @returns The local position
  67251. */
  67252. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  67253. if (mesh === void 0) { mesh = null; }
  67254. var result = BABYLON.Vector3.Zero();
  67255. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  67256. return result;
  67257. };
  67258. /**
  67259. * Get the local position of a point that is in world space and copy it to the result param.
  67260. * @param position The world position
  67261. * @param mesh The mesh that this bone is attached to.
  67262. * @param result The vector3 that the local position should be copied to.
  67263. */
  67264. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  67265. if (mesh === void 0) { mesh = null; }
  67266. var wm = null;
  67267. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67268. if (mesh) {
  67269. wm = mesh.getWorldMatrix();
  67270. }
  67271. this._skeleton.computeAbsoluteTransforms();
  67272. var tmat = Bone._tmpMats[0];
  67273. tmat.copyFrom(this.getAbsoluteTransform());
  67274. if (mesh && wm) {
  67275. tmat.multiplyToRef(wm, tmat);
  67276. }
  67277. tmat.invert();
  67278. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67279. };
  67280. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67281. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  67282. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67283. return Bone;
  67284. }(BABYLON.Node));
  67285. BABYLON.Bone = Bone;
  67286. })(BABYLON || (BABYLON = {}));
  67287. //# sourceMappingURL=babylon.bone.js.map
  67288. var BABYLON;
  67289. (function (BABYLON) {
  67290. var BoneIKController = /** @class */ (function () {
  67291. function BoneIKController(mesh, bone, options) {
  67292. this.targetPosition = BABYLON.Vector3.Zero();
  67293. this.poleTargetPosition = BABYLON.Vector3.Zero();
  67294. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  67295. this.poleAngle = 0;
  67296. this.slerpAmount = 1;
  67297. this._bone1Quat = BABYLON.Quaternion.Identity();
  67298. this._bone1Mat = BABYLON.Matrix.Identity();
  67299. this._bone2Ang = Math.PI;
  67300. this._maxAngle = Math.PI;
  67301. this._rightHandedSystem = false;
  67302. this._bendAxis = BABYLON.Vector3.Right();
  67303. this._slerping = false;
  67304. this._adjustRoll = 0;
  67305. this._bone2 = bone;
  67306. this._bone1 = bone.getParent();
  67307. if (!this._bone1) {
  67308. return;
  67309. }
  67310. this.mesh = mesh;
  67311. var bonePos = bone.getPosition();
  67312. if (bone.getAbsoluteTransform().determinant() > 0) {
  67313. this._rightHandedSystem = true;
  67314. this._bendAxis.x = 0;
  67315. this._bendAxis.y = 0;
  67316. this._bendAxis.z = -1;
  67317. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  67318. this._adjustRoll = Math.PI * .5;
  67319. this._bendAxis.z = 1;
  67320. }
  67321. }
  67322. if (this._bone1.length) {
  67323. var boneScale1 = this._bone1.getScale();
  67324. var boneScale2 = this._bone2.getScale();
  67325. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  67326. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  67327. }
  67328. else if (this._bone1.children[0]) {
  67329. mesh.computeWorldMatrix(true);
  67330. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  67331. var pos2 = this._bone2.getAbsolutePosition(mesh);
  67332. var pos3 = this._bone1.getAbsolutePosition(mesh);
  67333. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  67334. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  67335. }
  67336. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  67337. this.maxAngle = Math.PI;
  67338. if (options) {
  67339. if (options.targetMesh) {
  67340. this.targetMesh = options.targetMesh;
  67341. this.targetMesh.computeWorldMatrix(true);
  67342. }
  67343. if (options.poleTargetMesh) {
  67344. this.poleTargetMesh = options.poleTargetMesh;
  67345. this.poleTargetMesh.computeWorldMatrix(true);
  67346. }
  67347. else if (options.poleTargetBone) {
  67348. this.poleTargetBone = options.poleTargetBone;
  67349. }
  67350. else if (this._bone1.getParent()) {
  67351. this.poleTargetBone = this._bone1.getParent();
  67352. }
  67353. if (options.poleTargetLocalOffset) {
  67354. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  67355. }
  67356. if (options.poleAngle) {
  67357. this.poleAngle = options.poleAngle;
  67358. }
  67359. if (options.bendAxis) {
  67360. this._bendAxis.copyFrom(options.bendAxis);
  67361. }
  67362. if (options.maxAngle) {
  67363. this.maxAngle = options.maxAngle;
  67364. }
  67365. if (options.slerpAmount) {
  67366. this.slerpAmount = options.slerpAmount;
  67367. }
  67368. }
  67369. }
  67370. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  67371. get: function () {
  67372. return this._maxAngle;
  67373. },
  67374. set: function (value) {
  67375. this._setMaxAngle(value);
  67376. },
  67377. enumerable: true,
  67378. configurable: true
  67379. });
  67380. BoneIKController.prototype._setMaxAngle = function (ang) {
  67381. if (ang < 0) {
  67382. ang = 0;
  67383. }
  67384. if (ang > Math.PI || ang == undefined) {
  67385. ang = Math.PI;
  67386. }
  67387. this._maxAngle = ang;
  67388. var a = this._bone1Length;
  67389. var b = this._bone2Length;
  67390. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  67391. };
  67392. BoneIKController.prototype.update = function () {
  67393. var bone1 = this._bone1;
  67394. if (!bone1) {
  67395. return;
  67396. }
  67397. var target = this.targetPosition;
  67398. var poleTarget = this.poleTargetPosition;
  67399. var mat1 = BoneIKController._tmpMats[0];
  67400. var mat2 = BoneIKController._tmpMats[1];
  67401. if (this.targetMesh) {
  67402. target.copyFrom(this.targetMesh.getAbsolutePosition());
  67403. }
  67404. if (this.poleTargetBone) {
  67405. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  67406. }
  67407. else if (this.poleTargetMesh) {
  67408. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  67409. }
  67410. var bonePos = BoneIKController._tmpVecs[0];
  67411. var zaxis = BoneIKController._tmpVecs[1];
  67412. var xaxis = BoneIKController._tmpVecs[2];
  67413. var yaxis = BoneIKController._tmpVecs[3];
  67414. var upAxis = BoneIKController._tmpVecs[4];
  67415. var _tmpQuat = BoneIKController._tmpQuat;
  67416. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  67417. poleTarget.subtractToRef(bonePos, upAxis);
  67418. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  67419. upAxis.y = 1;
  67420. }
  67421. else {
  67422. upAxis.normalize();
  67423. }
  67424. target.subtractToRef(bonePos, yaxis);
  67425. yaxis.normalize();
  67426. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  67427. zaxis.normalize();
  67428. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  67429. xaxis.normalize();
  67430. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  67431. var a = this._bone1Length;
  67432. var b = this._bone2Length;
  67433. var c = BABYLON.Vector3.Distance(bonePos, target);
  67434. if (this._maxReach > 0) {
  67435. c = Math.min(this._maxReach, c);
  67436. }
  67437. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  67438. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  67439. if (acosa > 1) {
  67440. acosa = 1;
  67441. }
  67442. if (acosb > 1) {
  67443. acosb = 1;
  67444. }
  67445. if (acosa < -1) {
  67446. acosa = -1;
  67447. }
  67448. if (acosb < -1) {
  67449. acosb = -1;
  67450. }
  67451. var angA = Math.acos(acosa);
  67452. var angB = Math.acos(acosb);
  67453. var angC = -angA - angB;
  67454. if (this._rightHandedSystem) {
  67455. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  67456. mat2.multiplyToRef(mat1, mat1);
  67457. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  67458. mat2.multiplyToRef(mat1, mat1);
  67459. }
  67460. else {
  67461. var _tmpVec = BoneIKController._tmpVecs[5];
  67462. _tmpVec.copyFrom(this._bendAxis);
  67463. _tmpVec.x *= -1;
  67464. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  67465. mat2.multiplyToRef(mat1, mat1);
  67466. }
  67467. if (this.poleAngle) {
  67468. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  67469. mat1.multiplyToRef(mat2, mat1);
  67470. }
  67471. if (this._bone1) {
  67472. if (this.slerpAmount < 1) {
  67473. if (!this._slerping) {
  67474. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  67475. }
  67476. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  67477. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  67478. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  67479. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  67480. this._slerping = true;
  67481. }
  67482. else {
  67483. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  67484. this._bone1Mat.copyFrom(mat1);
  67485. this._slerping = false;
  67486. }
  67487. }
  67488. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  67489. this._bone2Ang = angC;
  67490. };
  67491. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67492. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  67493. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67494. return BoneIKController;
  67495. }());
  67496. BABYLON.BoneIKController = BoneIKController;
  67497. })(BABYLON || (BABYLON = {}));
  67498. //# sourceMappingURL=babylon.boneIKController.js.map
  67499. var BABYLON;
  67500. (function (BABYLON) {
  67501. var BoneLookController = /** @class */ (function () {
  67502. /**
  67503. * Create a BoneLookController
  67504. * @param mesh the mesh that the bone belongs to
  67505. * @param bone the bone that will be looking to the target
  67506. * @param target the target Vector3 to look at
  67507. * @param settings optional settings:
  67508. * - maxYaw: the maximum angle the bone will yaw to
  67509. * - minYaw: the minimum angle the bone will yaw to
  67510. * - maxPitch: the maximum angle the bone will pitch to
  67511. * - minPitch: the minimum angle the bone will yaw to
  67512. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  67513. * - upAxis: the up axis of the coordinate system
  67514. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67515. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  67516. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  67517. * - adjustYaw: used to make an adjustment to the yaw of the bone
  67518. * - adjustPitch: used to make an adjustment to the pitch of the bone
  67519. * - adjustRoll: used to make an adjustment to the roll of the bone
  67520. **/
  67521. function BoneLookController(mesh, bone, target, options) {
  67522. /**
  67523. * The up axis of the coordinate system that is used when the bone is rotated.
  67524. */
  67525. this.upAxis = BABYLON.Vector3.Up();
  67526. /**
  67527. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67528. */
  67529. this.upAxisSpace = BABYLON.Space.LOCAL;
  67530. /**
  67531. * Used to make an adjustment to the yaw of the bone.
  67532. */
  67533. this.adjustYaw = 0;
  67534. /**
  67535. * Used to make an adjustment to the pitch of the bone.
  67536. */
  67537. this.adjustPitch = 0;
  67538. /**
  67539. * Used to make an adjustment to the roll of the bone.
  67540. */
  67541. this.adjustRoll = 0;
  67542. /**
  67543. * 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).
  67544. */
  67545. this.slerpAmount = 1;
  67546. this._boneQuat = BABYLON.Quaternion.Identity();
  67547. this._slerping = false;
  67548. this._firstFrameSkipped = false;
  67549. this._fowardAxis = BABYLON.Vector3.Forward();
  67550. this.mesh = mesh;
  67551. this.bone = bone;
  67552. this.target = target;
  67553. if (options) {
  67554. if (options.adjustYaw) {
  67555. this.adjustYaw = options.adjustYaw;
  67556. }
  67557. if (options.adjustPitch) {
  67558. this.adjustPitch = options.adjustPitch;
  67559. }
  67560. if (options.adjustRoll) {
  67561. this.adjustRoll = options.adjustRoll;
  67562. }
  67563. if (options.maxYaw != null) {
  67564. this.maxYaw = options.maxYaw;
  67565. }
  67566. else {
  67567. this.maxYaw = Math.PI;
  67568. }
  67569. if (options.minYaw != null) {
  67570. this.minYaw = options.minYaw;
  67571. }
  67572. else {
  67573. this.minYaw = -Math.PI;
  67574. }
  67575. if (options.maxPitch != null) {
  67576. this.maxPitch = options.maxPitch;
  67577. }
  67578. else {
  67579. this.maxPitch = Math.PI;
  67580. }
  67581. if (options.minPitch != null) {
  67582. this.minPitch = options.minPitch;
  67583. }
  67584. else {
  67585. this.minPitch = -Math.PI;
  67586. }
  67587. if (options.slerpAmount != null) {
  67588. this.slerpAmount = options.slerpAmount;
  67589. }
  67590. if (options.upAxis != null) {
  67591. this.upAxis = options.upAxis;
  67592. }
  67593. if (options.upAxisSpace != null) {
  67594. this.upAxisSpace = options.upAxisSpace;
  67595. }
  67596. if (options.yawAxis != null || options.pitchAxis != null) {
  67597. var newYawAxis = BABYLON.Axis.Y;
  67598. var newPitchAxis = BABYLON.Axis.X;
  67599. if (options.yawAxis != null) {
  67600. newYawAxis = options.yawAxis.clone();
  67601. newYawAxis.normalize();
  67602. }
  67603. if (options.pitchAxis != null) {
  67604. newPitchAxis = options.pitchAxis.clone();
  67605. newPitchAxis.normalize();
  67606. }
  67607. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  67608. this._transformYawPitch = BABYLON.Matrix.Identity();
  67609. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  67610. this._transformYawPitchInv = this._transformYawPitch.clone();
  67611. this._transformYawPitch.invert();
  67612. }
  67613. }
  67614. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  67615. this.upAxisSpace = BABYLON.Space.LOCAL;
  67616. }
  67617. }
  67618. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  67619. /**
  67620. * Get/set the minimum yaw angle that the bone can look to.
  67621. */
  67622. get: function () {
  67623. return this._minYaw;
  67624. },
  67625. set: function (value) {
  67626. this._minYaw = value;
  67627. this._minYawSin = Math.sin(value);
  67628. this._minYawCos = Math.cos(value);
  67629. if (this._maxYaw != null) {
  67630. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67631. this._yawRange = this._maxYaw - this._minYaw;
  67632. }
  67633. },
  67634. enumerable: true,
  67635. configurable: true
  67636. });
  67637. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  67638. /**
  67639. * Get/set the maximum yaw angle that the bone can look to.
  67640. */
  67641. get: function () {
  67642. return this._maxYaw;
  67643. },
  67644. set: function (value) {
  67645. this._maxYaw = value;
  67646. this._maxYawSin = Math.sin(value);
  67647. this._maxYawCos = Math.cos(value);
  67648. if (this._minYaw != null) {
  67649. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67650. this._yawRange = this._maxYaw - this._minYaw;
  67651. }
  67652. },
  67653. enumerable: true,
  67654. configurable: true
  67655. });
  67656. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  67657. /**
  67658. * Get/set the minimum pitch angle that the bone can look to.
  67659. */
  67660. get: function () {
  67661. return this._minPitch;
  67662. },
  67663. set: function (value) {
  67664. this._minPitch = value;
  67665. this._minPitchTan = Math.tan(value);
  67666. },
  67667. enumerable: true,
  67668. configurable: true
  67669. });
  67670. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  67671. /**
  67672. * Get/set the maximum pitch angle that the bone can look to.
  67673. */
  67674. get: function () {
  67675. return this._maxPitch;
  67676. },
  67677. set: function (value) {
  67678. this._maxPitch = value;
  67679. this._maxPitchTan = Math.tan(value);
  67680. },
  67681. enumerable: true,
  67682. configurable: true
  67683. });
  67684. /**
  67685. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  67686. */
  67687. BoneLookController.prototype.update = function () {
  67688. //skip the first frame when slerping so that the mesh rotation is correct
  67689. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  67690. this._firstFrameSkipped = true;
  67691. return;
  67692. }
  67693. var bone = this.bone;
  67694. var bonePos = BoneLookController._tmpVecs[0];
  67695. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  67696. var target = this.target;
  67697. var _tmpMat1 = BoneLookController._tmpMats[0];
  67698. var _tmpMat2 = BoneLookController._tmpMats[1];
  67699. var mesh = this.mesh;
  67700. var parentBone = bone.getParent();
  67701. var upAxis = BoneLookController._tmpVecs[1];
  67702. upAxis.copyFrom(this.upAxis);
  67703. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  67704. if (this._transformYawPitch) {
  67705. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  67706. }
  67707. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  67708. }
  67709. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  67710. mesh.getDirectionToRef(upAxis, upAxis);
  67711. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  67712. upAxis.normalize();
  67713. }
  67714. }
  67715. var checkYaw = false;
  67716. var checkPitch = false;
  67717. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  67718. checkYaw = true;
  67719. }
  67720. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  67721. checkPitch = true;
  67722. }
  67723. if (checkYaw || checkPitch) {
  67724. var spaceMat = BoneLookController._tmpMats[2];
  67725. var spaceMatInv = BoneLookController._tmpMats[3];
  67726. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  67727. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  67728. }
  67729. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  67730. spaceMat.copyFrom(mesh.getWorldMatrix());
  67731. }
  67732. else {
  67733. var forwardAxis = BoneLookController._tmpVecs[2];
  67734. forwardAxis.copyFrom(this._fowardAxis);
  67735. if (this._transformYawPitch) {
  67736. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  67737. }
  67738. if (parentBone) {
  67739. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  67740. }
  67741. else {
  67742. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  67743. }
  67744. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  67745. rightAxis.normalize();
  67746. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  67747. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  67748. }
  67749. spaceMat.invertToRef(spaceMatInv);
  67750. var xzlen = null;
  67751. if (checkPitch) {
  67752. var localTarget = BoneLookController._tmpVecs[3];
  67753. target.subtractToRef(bonePos, localTarget);
  67754. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67755. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67756. var pitch = Math.atan2(localTarget.y, xzlen);
  67757. var newPitch = pitch;
  67758. if (pitch > this._maxPitch) {
  67759. localTarget.y = this._maxPitchTan * xzlen;
  67760. newPitch = this._maxPitch;
  67761. }
  67762. else if (pitch < this._minPitch) {
  67763. localTarget.y = this._minPitchTan * xzlen;
  67764. newPitch = this._minPitch;
  67765. }
  67766. if (pitch != newPitch) {
  67767. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67768. localTarget.addInPlace(bonePos);
  67769. target = localTarget;
  67770. }
  67771. }
  67772. if (checkYaw) {
  67773. var localTarget = BoneLookController._tmpVecs[4];
  67774. target.subtractToRef(bonePos, localTarget);
  67775. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67776. var yaw = Math.atan2(localTarget.x, localTarget.z);
  67777. var newYaw = yaw;
  67778. if (yaw > this._maxYaw || yaw < this._minYaw) {
  67779. if (xzlen == null) {
  67780. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67781. }
  67782. if (this._yawRange > Math.PI) {
  67783. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  67784. localTarget.z = this._maxYawCos * xzlen;
  67785. localTarget.x = this._maxYawSin * xzlen;
  67786. newYaw = this._maxYaw;
  67787. }
  67788. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  67789. localTarget.z = this._minYawCos * xzlen;
  67790. localTarget.x = this._minYawSin * xzlen;
  67791. newYaw = this._minYaw;
  67792. }
  67793. }
  67794. else {
  67795. if (yaw > this._maxYaw) {
  67796. localTarget.z = this._maxYawCos * xzlen;
  67797. localTarget.x = this._maxYawSin * xzlen;
  67798. newYaw = this._maxYaw;
  67799. }
  67800. else if (yaw < this._minYaw) {
  67801. localTarget.z = this._minYawCos * xzlen;
  67802. localTarget.x = this._minYawSin * xzlen;
  67803. newYaw = this._minYaw;
  67804. }
  67805. }
  67806. }
  67807. if (this._slerping && this._yawRange > Math.PI) {
  67808. //are we going to be crossing into the min/max region?
  67809. var boneFwd = BoneLookController._tmpVecs[8];
  67810. boneFwd.copyFrom(BABYLON.Axis.Z);
  67811. if (this._transformYawPitch) {
  67812. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  67813. }
  67814. var boneRotMat = BoneLookController._tmpMats[4];
  67815. this._boneQuat.toRotationMatrix(boneRotMat);
  67816. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  67817. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  67818. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  67819. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  67820. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  67821. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  67822. if (angBtwTar > angBtwMidYaw) {
  67823. if (xzlen == null) {
  67824. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67825. }
  67826. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  67827. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  67828. if (angBtwMin < angBtwMax) {
  67829. newYaw = boneYaw + Math.PI * .75;
  67830. localTarget.z = Math.cos(newYaw) * xzlen;
  67831. localTarget.x = Math.sin(newYaw) * xzlen;
  67832. }
  67833. else {
  67834. newYaw = boneYaw - Math.PI * .75;
  67835. localTarget.z = Math.cos(newYaw) * xzlen;
  67836. localTarget.x = Math.sin(newYaw) * xzlen;
  67837. }
  67838. }
  67839. }
  67840. if (yaw != newYaw) {
  67841. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67842. localTarget.addInPlace(bonePos);
  67843. target = localTarget;
  67844. }
  67845. }
  67846. }
  67847. var zaxis = BoneLookController._tmpVecs[5];
  67848. var xaxis = BoneLookController._tmpVecs[6];
  67849. var yaxis = BoneLookController._tmpVecs[7];
  67850. var _tmpQuat = BoneLookController._tmpQuat;
  67851. target.subtractToRef(bonePos, zaxis);
  67852. zaxis.normalize();
  67853. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  67854. xaxis.normalize();
  67855. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  67856. yaxis.normalize();
  67857. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  67858. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  67859. return;
  67860. }
  67861. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  67862. return;
  67863. }
  67864. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  67865. return;
  67866. }
  67867. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  67868. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  67869. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  67870. }
  67871. if (this.slerpAmount < 1) {
  67872. if (!this._slerping) {
  67873. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  67874. }
  67875. if (this._transformYawPitch) {
  67876. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67877. }
  67878. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  67879. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  67880. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  67881. this._slerping = true;
  67882. }
  67883. else {
  67884. if (this._transformYawPitch) {
  67885. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67886. }
  67887. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  67888. this._slerping = false;
  67889. }
  67890. };
  67891. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  67892. var angDiff = ang2 - ang1;
  67893. angDiff %= Math.PI * 2;
  67894. if (angDiff > Math.PI) {
  67895. angDiff -= Math.PI * 2;
  67896. }
  67897. else if (angDiff < -Math.PI) {
  67898. angDiff += Math.PI * 2;
  67899. }
  67900. return angDiff;
  67901. };
  67902. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  67903. ang1 %= (2 * Math.PI);
  67904. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67905. ang2 %= (2 * Math.PI);
  67906. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67907. var ab = 0;
  67908. if (ang1 < ang2) {
  67909. ab = ang2 - ang1;
  67910. }
  67911. else {
  67912. ab = ang1 - ang2;
  67913. }
  67914. if (ab > Math.PI) {
  67915. ab = Math.PI * 2 - ab;
  67916. }
  67917. return ab;
  67918. };
  67919. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  67920. ang %= (2 * Math.PI);
  67921. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  67922. ang1 %= (2 * Math.PI);
  67923. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67924. ang2 %= (2 * Math.PI);
  67925. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67926. if (ang1 < ang2) {
  67927. if (ang > ang1 && ang < ang2) {
  67928. return true;
  67929. }
  67930. }
  67931. else {
  67932. if (ang > ang2 && ang < ang1) {
  67933. return true;
  67934. }
  67935. }
  67936. return false;
  67937. };
  67938. 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()];
  67939. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  67940. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67941. return BoneLookController;
  67942. }());
  67943. BABYLON.BoneLookController = BoneLookController;
  67944. })(BABYLON || (BABYLON = {}));
  67945. //# sourceMappingURL=babylon.boneLookController.js.map
  67946. var BABYLON;
  67947. (function (BABYLON) {
  67948. var Skeleton = /** @class */ (function () {
  67949. function Skeleton(name, id, scene) {
  67950. this.name = name;
  67951. this.id = id;
  67952. this.bones = new Array();
  67953. this.needInitialSkinMatrix = false;
  67954. this._isDirty = true;
  67955. this._meshesWithPoseMatrix = new Array();
  67956. this._identity = BABYLON.Matrix.Identity();
  67957. this._ranges = {};
  67958. this._lastAbsoluteTransformsUpdateId = -1;
  67959. // Events
  67960. /**
  67961. * An event triggered before computing the skeleton's matrices
  67962. * @type {BABYLON.Observable}
  67963. */
  67964. this.onBeforeComputeObservable = new BABYLON.Observable();
  67965. this.bones = [];
  67966. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67967. scene.skeletons.push(this);
  67968. //make sure it will recalculate the matrix next time prepare is called.
  67969. this._isDirty = true;
  67970. }
  67971. // Members
  67972. Skeleton.prototype.getTransformMatrices = function (mesh) {
  67973. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  67974. return mesh._bonesTransformMatrices;
  67975. }
  67976. if (!this._transformMatrices) {
  67977. this.prepare();
  67978. }
  67979. return this._transformMatrices;
  67980. };
  67981. Skeleton.prototype.getScene = function () {
  67982. return this._scene;
  67983. };
  67984. // Methods
  67985. /**
  67986. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  67987. */
  67988. Skeleton.prototype.toString = function (fullDetails) {
  67989. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  67990. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  67991. if (fullDetails) {
  67992. ret += ", Ranges: {";
  67993. var first = true;
  67994. for (var name_1 in this._ranges) {
  67995. if (first) {
  67996. ret += ", ";
  67997. first = false;
  67998. }
  67999. ret += name_1;
  68000. }
  68001. ret += "}";
  68002. }
  68003. return ret;
  68004. };
  68005. /**
  68006. * Get bone's index searching by name
  68007. * @param {string} name is bone's name to search for
  68008. * @return {number} Indice of the bone. Returns -1 if not found
  68009. */
  68010. Skeleton.prototype.getBoneIndexByName = function (name) {
  68011. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  68012. if (this.bones[boneIndex].name === name) {
  68013. return boneIndex;
  68014. }
  68015. }
  68016. return -1;
  68017. };
  68018. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  68019. // check name not already in use
  68020. if (!this._ranges[name]) {
  68021. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  68022. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68023. if (this.bones[i].animations[0]) {
  68024. this.bones[i].animations[0].createRange(name, from, to);
  68025. }
  68026. }
  68027. }
  68028. };
  68029. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  68030. if (deleteFrames === void 0) { deleteFrames = true; }
  68031. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68032. if (this.bones[i].animations[0]) {
  68033. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  68034. }
  68035. }
  68036. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  68037. };
  68038. Skeleton.prototype.getAnimationRange = function (name) {
  68039. return this._ranges[name];
  68040. };
  68041. /**
  68042. * Returns as an Array, all AnimationRanges defined on this skeleton
  68043. */
  68044. Skeleton.prototype.getAnimationRanges = function () {
  68045. var animationRanges = [];
  68046. var name;
  68047. var i = 0;
  68048. for (name in this._ranges) {
  68049. animationRanges[i] = this._ranges[name];
  68050. i++;
  68051. }
  68052. return animationRanges;
  68053. };
  68054. /**
  68055. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  68056. */
  68057. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  68058. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68059. if (this._ranges[name] || !source.getAnimationRange(name)) {
  68060. return false;
  68061. }
  68062. var ret = true;
  68063. var frameOffset = this._getHighestAnimationFrame() + 1;
  68064. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  68065. var boneDict = {};
  68066. var sourceBones = source.bones;
  68067. var nBones;
  68068. var i;
  68069. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  68070. boneDict[sourceBones[i].name] = sourceBones[i];
  68071. }
  68072. if (this.bones.length !== sourceBones.length) {
  68073. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  68074. ret = false;
  68075. }
  68076. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  68077. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  68078. var boneName = this.bones[i].name;
  68079. var sourceBone = boneDict[boneName];
  68080. if (sourceBone) {
  68081. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  68082. }
  68083. else {
  68084. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  68085. ret = false;
  68086. }
  68087. }
  68088. // do not call createAnimationRange(), since it also is done to bones, which was already done
  68089. var range = source.getAnimationRange(name);
  68090. if (range) {
  68091. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  68092. }
  68093. return ret;
  68094. };
  68095. Skeleton.prototype.returnToRest = function () {
  68096. for (var index = 0; index < this.bones.length; index++) {
  68097. this.bones[index].returnToRest();
  68098. }
  68099. };
  68100. Skeleton.prototype._getHighestAnimationFrame = function () {
  68101. var ret = 0;
  68102. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68103. if (this.bones[i].animations[0]) {
  68104. var highest = this.bones[i].animations[0].getHighestFrame();
  68105. if (ret < highest) {
  68106. ret = highest;
  68107. }
  68108. }
  68109. }
  68110. return ret;
  68111. };
  68112. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  68113. var range = this.getAnimationRange(name);
  68114. if (!range) {
  68115. return null;
  68116. }
  68117. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  68118. };
  68119. Skeleton.prototype._markAsDirty = function () {
  68120. this._isDirty = true;
  68121. };
  68122. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  68123. this._meshesWithPoseMatrix.push(mesh);
  68124. };
  68125. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  68126. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  68127. if (index > -1) {
  68128. this._meshesWithPoseMatrix.splice(index, 1);
  68129. }
  68130. };
  68131. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  68132. this.onBeforeComputeObservable.notifyObservers(this);
  68133. for (var index = 0; index < this.bones.length; index++) {
  68134. var bone = this.bones[index];
  68135. var parentBone = bone.getParent();
  68136. if (parentBone) {
  68137. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  68138. }
  68139. else {
  68140. if (initialSkinMatrix) {
  68141. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  68142. }
  68143. else {
  68144. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  68145. }
  68146. }
  68147. if (bone._index !== -1) {
  68148. var mappedIndex = bone._index === null ? index : bone._index;
  68149. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  68150. }
  68151. }
  68152. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  68153. };
  68154. Skeleton.prototype.prepare = function () {
  68155. if (!this._isDirty) {
  68156. return;
  68157. }
  68158. if (this.needInitialSkinMatrix) {
  68159. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  68160. var mesh = this._meshesWithPoseMatrix[index];
  68161. var poseMatrix = mesh.getPoseMatrix();
  68162. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  68163. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68164. }
  68165. if (this._synchronizedWithMesh !== mesh) {
  68166. this._synchronizedWithMesh = mesh;
  68167. // Prepare bones
  68168. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  68169. var bone = this.bones[boneIndex];
  68170. if (!bone.getParent()) {
  68171. var matrix = bone.getBaseMatrix();
  68172. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  68173. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  68174. }
  68175. }
  68176. }
  68177. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  68178. }
  68179. }
  68180. else {
  68181. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  68182. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68183. }
  68184. this._computeTransformMatrices(this._transformMatrices, null);
  68185. }
  68186. this._isDirty = false;
  68187. this._scene._activeBones.addCount(this.bones.length, false);
  68188. };
  68189. Skeleton.prototype.getAnimatables = function () {
  68190. if (!this._animatables || this._animatables.length !== this.bones.length) {
  68191. this._animatables = [];
  68192. for (var index = 0; index < this.bones.length; index++) {
  68193. this._animatables.push(this.bones[index]);
  68194. }
  68195. }
  68196. return this._animatables;
  68197. };
  68198. Skeleton.prototype.clone = function (name, id) {
  68199. var result = new Skeleton(name, id || name, this._scene);
  68200. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68201. for (var index = 0; index < this.bones.length; index++) {
  68202. var source = this.bones[index];
  68203. var parentBone = null;
  68204. var parent_1 = source.getParent();
  68205. if (parent_1) {
  68206. var parentIndex = this.bones.indexOf(parent_1);
  68207. parentBone = result.bones[parentIndex];
  68208. }
  68209. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  68210. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  68211. }
  68212. if (this._ranges) {
  68213. result._ranges = {};
  68214. for (var rangeName in this._ranges) {
  68215. var range = this._ranges[rangeName];
  68216. if (range) {
  68217. result._ranges[rangeName] = range.clone();
  68218. }
  68219. }
  68220. }
  68221. this._isDirty = true;
  68222. return result;
  68223. };
  68224. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  68225. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  68226. this.bones.forEach(function (bone) {
  68227. bone.animations.forEach(function (animation) {
  68228. animation.enableBlending = true;
  68229. animation.blendingSpeed = blendingSpeed;
  68230. });
  68231. });
  68232. };
  68233. Skeleton.prototype.dispose = function () {
  68234. this._meshesWithPoseMatrix = [];
  68235. // Animations
  68236. this.getScene().stopAnimation(this);
  68237. // Remove from scene
  68238. this.getScene().removeSkeleton(this);
  68239. };
  68240. Skeleton.prototype.serialize = function () {
  68241. var serializationObject = {};
  68242. serializationObject.name = this.name;
  68243. serializationObject.id = this.id;
  68244. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  68245. serializationObject.bones = [];
  68246. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68247. for (var index = 0; index < this.bones.length; index++) {
  68248. var bone = this.bones[index];
  68249. var parent_2 = bone.getParent();
  68250. var serializedBone = {
  68251. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  68252. name: bone.name,
  68253. matrix: bone.getBaseMatrix().toArray(),
  68254. rest: bone.getRestPose().toArray()
  68255. };
  68256. serializationObject.bones.push(serializedBone);
  68257. if (bone.length) {
  68258. serializedBone.length = bone.length;
  68259. }
  68260. if (bone.animations && bone.animations.length > 0) {
  68261. serializedBone.animation = bone.animations[0].serialize();
  68262. }
  68263. serializationObject.ranges = [];
  68264. for (var name in this._ranges) {
  68265. var source = this._ranges[name];
  68266. if (!source) {
  68267. continue;
  68268. }
  68269. var range = {};
  68270. range.name = name;
  68271. range.from = source.from;
  68272. range.to = source.to;
  68273. serializationObject.ranges.push(range);
  68274. }
  68275. }
  68276. return serializationObject;
  68277. };
  68278. Skeleton.Parse = function (parsedSkeleton, scene) {
  68279. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  68280. if (parsedSkeleton.dimensionsAtRest) {
  68281. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  68282. }
  68283. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  68284. var index;
  68285. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  68286. var parsedBone = parsedSkeleton.bones[index];
  68287. var parentBone = null;
  68288. if (parsedBone.parentBoneIndex > -1) {
  68289. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  68290. }
  68291. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  68292. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  68293. if (parsedBone.length) {
  68294. bone.length = parsedBone.length;
  68295. }
  68296. if (parsedBone.animation) {
  68297. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  68298. }
  68299. }
  68300. // placed after bones, so createAnimationRange can cascade down
  68301. if (parsedSkeleton.ranges) {
  68302. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  68303. var data = parsedSkeleton.ranges[index];
  68304. skeleton.createAnimationRange(data.name, data.from, data.to);
  68305. }
  68306. }
  68307. return skeleton;
  68308. };
  68309. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  68310. if (forceUpdate === void 0) { forceUpdate = false; }
  68311. var renderId = this._scene.getRenderId();
  68312. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  68313. this.bones[0].computeAbsoluteTransforms();
  68314. this._lastAbsoluteTransformsUpdateId = renderId;
  68315. }
  68316. };
  68317. Skeleton.prototype.getPoseMatrix = function () {
  68318. var poseMatrix = null;
  68319. if (this._meshesWithPoseMatrix.length > 0) {
  68320. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  68321. }
  68322. return poseMatrix;
  68323. };
  68324. Skeleton.prototype.sortBones = function () {
  68325. var bones = new Array();
  68326. var visited = new Array(this.bones.length);
  68327. for (var index = 0; index < this.bones.length; index++) {
  68328. this._sortBones(index, bones, visited);
  68329. }
  68330. this.bones = bones;
  68331. };
  68332. Skeleton.prototype._sortBones = function (index, bones, visited) {
  68333. if (visited[index]) {
  68334. return;
  68335. }
  68336. visited[index] = true;
  68337. var bone = this.bones[index];
  68338. if (bone._index === undefined) {
  68339. bone._index = index;
  68340. }
  68341. var parentBone = bone.getParent();
  68342. if (parentBone) {
  68343. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  68344. }
  68345. bones.push(bone);
  68346. };
  68347. return Skeleton;
  68348. }());
  68349. BABYLON.Skeleton = Skeleton;
  68350. })(BABYLON || (BABYLON = {}));
  68351. //# sourceMappingURL=babylon.skeleton.js.map
  68352. var BABYLON;
  68353. (function (BABYLON) {
  68354. var SphericalPolynomial = /** @class */ (function () {
  68355. function SphericalPolynomial() {
  68356. this.x = BABYLON.Vector3.Zero();
  68357. this.y = BABYLON.Vector3.Zero();
  68358. this.z = BABYLON.Vector3.Zero();
  68359. this.xx = BABYLON.Vector3.Zero();
  68360. this.yy = BABYLON.Vector3.Zero();
  68361. this.zz = BABYLON.Vector3.Zero();
  68362. this.xy = BABYLON.Vector3.Zero();
  68363. this.yz = BABYLON.Vector3.Zero();
  68364. this.zx = BABYLON.Vector3.Zero();
  68365. }
  68366. SphericalPolynomial.prototype.addAmbient = function (color) {
  68367. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68368. this.xx = this.xx.add(colorVector);
  68369. this.yy = this.yy.add(colorVector);
  68370. this.zz = this.zz.add(colorVector);
  68371. };
  68372. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  68373. var result = new SphericalPolynomial();
  68374. result.x = harmonics.L11.scale(1.02333);
  68375. result.y = harmonics.L1_1.scale(1.02333);
  68376. result.z = harmonics.L10.scale(1.02333);
  68377. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  68378. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  68379. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  68380. result.yz = harmonics.L2_1.scale(0.858086);
  68381. result.zx = harmonics.L21.scale(0.858086);
  68382. result.xy = harmonics.L2_2.scale(0.858086);
  68383. result.scale(1.0 / Math.PI);
  68384. return result;
  68385. };
  68386. SphericalPolynomial.prototype.scale = function (scale) {
  68387. this.x = this.x.scale(scale);
  68388. this.y = this.y.scale(scale);
  68389. this.z = this.z.scale(scale);
  68390. this.xx = this.xx.scale(scale);
  68391. this.yy = this.yy.scale(scale);
  68392. this.zz = this.zz.scale(scale);
  68393. this.yz = this.yz.scale(scale);
  68394. this.zx = this.zx.scale(scale);
  68395. this.xy = this.xy.scale(scale);
  68396. };
  68397. return SphericalPolynomial;
  68398. }());
  68399. BABYLON.SphericalPolynomial = SphericalPolynomial;
  68400. var SphericalHarmonics = /** @class */ (function () {
  68401. function SphericalHarmonics() {
  68402. this.L00 = BABYLON.Vector3.Zero();
  68403. this.L1_1 = BABYLON.Vector3.Zero();
  68404. this.L10 = BABYLON.Vector3.Zero();
  68405. this.L11 = BABYLON.Vector3.Zero();
  68406. this.L2_2 = BABYLON.Vector3.Zero();
  68407. this.L2_1 = BABYLON.Vector3.Zero();
  68408. this.L20 = BABYLON.Vector3.Zero();
  68409. this.L21 = BABYLON.Vector3.Zero();
  68410. this.L22 = BABYLON.Vector3.Zero();
  68411. }
  68412. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  68413. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68414. var c = colorVector.scale(deltaSolidAngle);
  68415. this.L00 = this.L00.add(c.scale(0.282095));
  68416. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  68417. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  68418. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  68419. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  68420. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  68421. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  68422. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  68423. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  68424. };
  68425. SphericalHarmonics.prototype.scale = function (scale) {
  68426. this.L00 = this.L00.scale(scale);
  68427. this.L1_1 = this.L1_1.scale(scale);
  68428. this.L10 = this.L10.scale(scale);
  68429. this.L11 = this.L11.scale(scale);
  68430. this.L2_2 = this.L2_2.scale(scale);
  68431. this.L2_1 = this.L2_1.scale(scale);
  68432. this.L20 = this.L20.scale(scale);
  68433. this.L21 = this.L21.scale(scale);
  68434. this.L22 = this.L22.scale(scale);
  68435. };
  68436. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  68437. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  68438. //
  68439. // E_lm = A_l * L_lm
  68440. //
  68441. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  68442. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  68443. // the scaling factors are given in equation 9.
  68444. // Constant (Band 0)
  68445. this.L00 = this.L00.scale(3.141593);
  68446. // Linear (Band 1)
  68447. this.L1_1 = this.L1_1.scale(2.094395);
  68448. this.L10 = this.L10.scale(2.094395);
  68449. this.L11 = this.L11.scale(2.094395);
  68450. // Quadratic (Band 2)
  68451. this.L2_2 = this.L2_2.scale(0.785398);
  68452. this.L2_1 = this.L2_1.scale(0.785398);
  68453. this.L20 = this.L20.scale(0.785398);
  68454. this.L21 = this.L21.scale(0.785398);
  68455. this.L22 = this.L22.scale(0.785398);
  68456. };
  68457. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  68458. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  68459. // L = (1/pi) * E * rho
  68460. //
  68461. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  68462. this.scale(1.0 / Math.PI);
  68463. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  68464. // (The pixel shader must apply albedo after texture fetches, etc).
  68465. };
  68466. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  68467. var result = new SphericalHarmonics();
  68468. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  68469. result.L1_1 = polynomial.y.scale(0.977204);
  68470. result.L10 = polynomial.z.scale(0.977204);
  68471. result.L11 = polynomial.x.scale(0.977204);
  68472. result.L2_2 = polynomial.xy.scale(1.16538);
  68473. result.L2_1 = polynomial.yz.scale(1.16538);
  68474. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  68475. result.L21 = polynomial.zx.scale(1.16538);
  68476. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  68477. result.scale(Math.PI);
  68478. return result;
  68479. };
  68480. return SphericalHarmonics;
  68481. }());
  68482. BABYLON.SphericalHarmonics = SphericalHarmonics;
  68483. })(BABYLON || (BABYLON = {}));
  68484. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  68485. var BABYLON;
  68486. (function (BABYLON) {
  68487. var FileFaceOrientation = /** @class */ (function () {
  68488. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  68489. this.name = name;
  68490. this.worldAxisForNormal = worldAxisForNormal;
  68491. this.worldAxisForFileX = worldAxisForFileX;
  68492. this.worldAxisForFileY = worldAxisForFileY;
  68493. }
  68494. return FileFaceOrientation;
  68495. }());
  68496. ;
  68497. /**
  68498. * Helper class dealing with the extraction of spherical polynomial dataArray
  68499. * from a cube map.
  68500. */
  68501. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  68502. function CubeMapToSphericalPolynomialTools() {
  68503. }
  68504. /**
  68505. * Converts a texture to the according Spherical Polynomial data.
  68506. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68507. *
  68508. * @param texture The texture to extract the information from.
  68509. * @return The Spherical Polynomial data.
  68510. */
  68511. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  68512. if (!texture.isCube) {
  68513. // Only supports cube Textures currently.
  68514. return null;
  68515. }
  68516. var size = texture.getSize().width;
  68517. var right = texture.readPixels(0);
  68518. var left = texture.readPixels(1);
  68519. var up;
  68520. var down;
  68521. if (texture.isRenderTarget) {
  68522. up = texture.readPixels(3);
  68523. down = texture.readPixels(2);
  68524. }
  68525. else {
  68526. up = texture.readPixels(2);
  68527. down = texture.readPixels(3);
  68528. }
  68529. var front = texture.readPixels(4);
  68530. var back = texture.readPixels(5);
  68531. var gammaSpace = texture.gammaSpace;
  68532. // Always read as RGBA.
  68533. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  68534. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68535. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68536. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68537. }
  68538. var cubeInfo = {
  68539. size: size,
  68540. right: right,
  68541. left: left,
  68542. up: up,
  68543. down: down,
  68544. front: front,
  68545. back: back,
  68546. format: format,
  68547. type: type,
  68548. gammaSpace: gammaSpace,
  68549. };
  68550. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  68551. };
  68552. /**
  68553. * Converts a cubemap to the according Spherical Polynomial data.
  68554. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68555. *
  68556. * @param cubeInfo The Cube map to extract the information from.
  68557. * @return The Spherical Polynomial data.
  68558. */
  68559. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  68560. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  68561. var totalSolidAngle = 0.0;
  68562. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  68563. var du = 2.0 / cubeInfo.size;
  68564. var dv = du;
  68565. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  68566. var minUV = du * 0.5 - 1.0;
  68567. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68568. var fileFace = this.FileFaces[faceIndex];
  68569. var dataArray = cubeInfo[fileFace.name];
  68570. var v = minUV;
  68571. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  68572. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  68573. // Because SP is still linear, so summation is fine in that basis.
  68574. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  68575. for (var y = 0; y < cubeInfo.size; y++) {
  68576. var u = minUV;
  68577. for (var x = 0; x < cubeInfo.size; x++) {
  68578. // World direction (not normalised)
  68579. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  68580. worldDirection.normalize();
  68581. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  68582. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  68583. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  68584. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  68585. // Handle Integer types.
  68586. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68587. r /= 255;
  68588. g /= 255;
  68589. b /= 255;
  68590. }
  68591. // Handle Gamma space textures.
  68592. if (cubeInfo.gammaSpace) {
  68593. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  68594. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  68595. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  68596. }
  68597. var color = new BABYLON.Color3(r, g, b);
  68598. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  68599. totalSolidAngle += deltaSolidAngle;
  68600. u += du;
  68601. }
  68602. v += dv;
  68603. }
  68604. }
  68605. // Solid angle for entire sphere is 4*pi
  68606. var sphereSolidAngle = 4.0 * Math.PI;
  68607. // Adjust the solid angle to allow for how many faces we processed.
  68608. var facesProcessed = 6.0;
  68609. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  68610. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  68611. // This is needed because the numerical integration over the cube uses a
  68612. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  68613. // and also to compensate for accumulative error due to float precision in the summation.
  68614. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  68615. sphericalHarmonics.scale(correctionFactor);
  68616. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  68617. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  68618. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  68619. };
  68620. CubeMapToSphericalPolynomialTools.FileFaces = [
  68621. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  68622. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  68623. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  68624. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  68625. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  68626. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  68627. ];
  68628. return CubeMapToSphericalPolynomialTools;
  68629. }());
  68630. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  68631. })(BABYLON || (BABYLON = {}));
  68632. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  68633. var BABYLON;
  68634. (function (BABYLON) {
  68635. /**
  68636. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  68637. */
  68638. var PanoramaToCubeMapTools = /** @class */ (function () {
  68639. function PanoramaToCubeMapTools() {
  68640. }
  68641. /**
  68642. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  68643. *
  68644. * @param float32Array The source data.
  68645. * @param inputWidth The width of the input panorama.
  68646. * @param inputhHeight The height of the input panorama.
  68647. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  68648. * @return The cubemap data
  68649. */
  68650. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  68651. if (!float32Array) {
  68652. throw "ConvertPanoramaToCubemap: input cannot be null";
  68653. }
  68654. if (float32Array.length != inputWidth * inputHeight * 3) {
  68655. throw "ConvertPanoramaToCubemap: input size is wrong";
  68656. }
  68657. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  68658. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  68659. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  68660. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  68661. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  68662. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  68663. return {
  68664. front: textureFront,
  68665. back: textureBack,
  68666. left: textureLeft,
  68667. right: textureRight,
  68668. up: textureUp,
  68669. down: textureDown,
  68670. size: size,
  68671. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  68672. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  68673. gammaSpace: false,
  68674. };
  68675. };
  68676. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  68677. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  68678. var textureArray = new Float32Array(buffer);
  68679. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  68680. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  68681. var dy = 1 / texSize;
  68682. var fy = 0;
  68683. for (var y = 0; y < texSize; y++) {
  68684. var xv1 = faceData[0];
  68685. var xv2 = faceData[2];
  68686. for (var x = 0; x < texSize; x++) {
  68687. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  68688. v.normalize();
  68689. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  68690. // 3 channels per pixels
  68691. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  68692. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  68693. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  68694. xv1 = xv1.add(rotDX1);
  68695. xv2 = xv2.add(rotDX2);
  68696. }
  68697. fy += dy;
  68698. }
  68699. return textureArray;
  68700. };
  68701. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  68702. var theta = Math.atan2(vDir.z, vDir.x);
  68703. var phi = Math.acos(vDir.y);
  68704. while (theta < -Math.PI)
  68705. theta += 2 * Math.PI;
  68706. while (theta > Math.PI)
  68707. theta -= 2 * Math.PI;
  68708. var dx = theta / Math.PI;
  68709. var dy = phi / Math.PI;
  68710. // recenter.
  68711. dx = dx * 0.5 + 0.5;
  68712. var px = Math.round(dx * inputWidth);
  68713. if (px < 0)
  68714. px = 0;
  68715. else if (px >= inputWidth)
  68716. px = inputWidth - 1;
  68717. var py = Math.round(dy * inputHeight);
  68718. if (py < 0)
  68719. py = 0;
  68720. else if (py >= inputHeight)
  68721. py = inputHeight - 1;
  68722. var inputY = (inputHeight - py - 1);
  68723. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  68724. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  68725. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  68726. return {
  68727. r: r,
  68728. g: g,
  68729. b: b
  68730. };
  68731. };
  68732. PanoramaToCubeMapTools.FACE_FRONT = [
  68733. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68734. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68735. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68736. new BABYLON.Vector3(1.0, 1.0, -1.0)
  68737. ];
  68738. PanoramaToCubeMapTools.FACE_BACK = [
  68739. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68740. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68741. new BABYLON.Vector3(1.0, 1.0, 1.0),
  68742. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  68743. ];
  68744. PanoramaToCubeMapTools.FACE_RIGHT = [
  68745. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68746. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68747. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68748. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68749. ];
  68750. PanoramaToCubeMapTools.FACE_LEFT = [
  68751. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68752. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68753. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68754. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  68755. ];
  68756. PanoramaToCubeMapTools.FACE_DOWN = [
  68757. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68758. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68759. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68760. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68761. ];
  68762. PanoramaToCubeMapTools.FACE_UP = [
  68763. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68764. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68765. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68766. new BABYLON.Vector3(1.0, -1.0, -1.0)
  68767. ];
  68768. return PanoramaToCubeMapTools;
  68769. }());
  68770. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  68771. })(BABYLON || (BABYLON = {}));
  68772. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  68773. var BABYLON;
  68774. (function (BABYLON) {
  68775. ;
  68776. /**
  68777. * This groups tools to convert HDR texture to native colors array.
  68778. */
  68779. var HDRTools = /** @class */ (function () {
  68780. function HDRTools() {
  68781. }
  68782. HDRTools.Ldexp = function (mantissa, exponent) {
  68783. if (exponent > 1023) {
  68784. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  68785. }
  68786. if (exponent < -1074) {
  68787. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  68788. }
  68789. return mantissa * Math.pow(2, exponent);
  68790. };
  68791. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  68792. if (exponent > 0) {
  68793. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  68794. float32array[index + 0] = red * exponent;
  68795. float32array[index + 1] = green * exponent;
  68796. float32array[index + 2] = blue * exponent;
  68797. }
  68798. else {
  68799. float32array[index + 0] = 0;
  68800. float32array[index + 1] = 0;
  68801. float32array[index + 2] = 0;
  68802. }
  68803. };
  68804. HDRTools.readStringLine = function (uint8array, startIndex) {
  68805. var line = "";
  68806. var character = "";
  68807. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  68808. character = String.fromCharCode(uint8array[i]);
  68809. if (character == "\n") {
  68810. break;
  68811. }
  68812. line += character;
  68813. }
  68814. return line;
  68815. };
  68816. /**
  68817. * Reads header information from an RGBE texture stored in a native array.
  68818. * More information on this format are available here:
  68819. * https://en.wikipedia.org/wiki/RGBE_image_format
  68820. *
  68821. * @param uint8array The binary file stored in native array.
  68822. * @return The header information.
  68823. */
  68824. HDRTools.RGBE_ReadHeader = function (uint8array) {
  68825. var height = 0;
  68826. var width = 0;
  68827. var line = this.readStringLine(uint8array, 0);
  68828. if (line[0] != '#' || line[1] != '?') {
  68829. throw "Bad HDR Format.";
  68830. }
  68831. var endOfHeader = false;
  68832. var findFormat = false;
  68833. var lineIndex = 0;
  68834. do {
  68835. lineIndex += (line.length + 1);
  68836. line = this.readStringLine(uint8array, lineIndex);
  68837. if (line == "FORMAT=32-bit_rle_rgbe") {
  68838. findFormat = true;
  68839. }
  68840. else if (line.length == 0) {
  68841. endOfHeader = true;
  68842. }
  68843. } while (!endOfHeader);
  68844. if (!findFormat) {
  68845. throw "HDR Bad header format, unsupported FORMAT";
  68846. }
  68847. lineIndex += (line.length + 1);
  68848. line = this.readStringLine(uint8array, lineIndex);
  68849. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  68850. var match = sizeRegexp.exec(line);
  68851. // TODO. Support +Y and -X if needed.
  68852. if (!match || match.length < 3) {
  68853. throw "HDR Bad header format, no size";
  68854. }
  68855. width = parseInt(match[2]);
  68856. height = parseInt(match[1]);
  68857. if (width < 8 || width > 0x7fff) {
  68858. throw "HDR Bad header format, unsupported size";
  68859. }
  68860. lineIndex += (line.length + 1);
  68861. return {
  68862. height: height,
  68863. width: width,
  68864. dataPosition: lineIndex
  68865. };
  68866. };
  68867. /**
  68868. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  68869. * This RGBE texture needs to store the information as a panorama.
  68870. *
  68871. * More information on this format are available here:
  68872. * https://en.wikipedia.org/wiki/RGBE_image_format
  68873. *
  68874. * @param buffer The binary file stored in an array buffer.
  68875. * @param size The expected size of the extracted cubemap.
  68876. * @return The Cube Map information.
  68877. */
  68878. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  68879. var uint8array = new Uint8Array(buffer);
  68880. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  68881. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68882. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  68883. return cubeMapData;
  68884. };
  68885. /**
  68886. * Returns the pixels data extracted from an RGBE texture.
  68887. * This pixels will be stored left to right up to down in the R G B order in one array.
  68888. *
  68889. * More information on this format are available here:
  68890. * https://en.wikipedia.org/wiki/RGBE_image_format
  68891. *
  68892. * @param uint8array The binary file stored in an array buffer.
  68893. * @param hdrInfo The header information of the file.
  68894. * @return The pixels data in RGB right to left up to down order.
  68895. */
  68896. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  68897. // Keep for multi format supports.
  68898. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68899. };
  68900. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  68901. var num_scanlines = hdrInfo.height;
  68902. var scanline_width = hdrInfo.width;
  68903. var a, b, c, d, count;
  68904. var dataIndex = hdrInfo.dataPosition;
  68905. var index = 0, endIndex = 0, i = 0;
  68906. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  68907. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  68908. // 3 channels of 4 bytes per pixel in float.
  68909. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  68910. var resultArray = new Float32Array(resultBuffer);
  68911. // read in each successive scanline
  68912. while (num_scanlines > 0) {
  68913. a = uint8array[dataIndex++];
  68914. b = uint8array[dataIndex++];
  68915. c = uint8array[dataIndex++];
  68916. d = uint8array[dataIndex++];
  68917. if (a != 2 || b != 2 || (c & 0x80)) {
  68918. // this file is not run length encoded
  68919. throw "HDR Bad header format, not RLE";
  68920. }
  68921. if (((c << 8) | d) != scanline_width) {
  68922. throw "HDR Bad header format, wrong scan line width";
  68923. }
  68924. index = 0;
  68925. // read each of the four channels for the scanline into the buffer
  68926. for (i = 0; i < 4; i++) {
  68927. endIndex = (i + 1) * scanline_width;
  68928. while (index < endIndex) {
  68929. a = uint8array[dataIndex++];
  68930. b = uint8array[dataIndex++];
  68931. if (a > 128) {
  68932. // a run of the same value
  68933. count = a - 128;
  68934. if ((count == 0) || (count > endIndex - index)) {
  68935. throw "HDR Bad Format, bad scanline data (run)";
  68936. }
  68937. while (count-- > 0) {
  68938. scanLineArray[index++] = b;
  68939. }
  68940. }
  68941. else {
  68942. // a non-run
  68943. count = a;
  68944. if ((count == 0) || (count > endIndex - index)) {
  68945. throw "HDR Bad Format, bad scanline data (non-run)";
  68946. }
  68947. scanLineArray[index++] = b;
  68948. if (--count > 0) {
  68949. for (var j = 0; j < count; j++) {
  68950. scanLineArray[index++] = uint8array[dataIndex++];
  68951. }
  68952. }
  68953. }
  68954. }
  68955. }
  68956. // now convert data from buffer into floats
  68957. for (i = 0; i < scanline_width; i++) {
  68958. a = scanLineArray[i];
  68959. b = scanLineArray[i + scanline_width];
  68960. c = scanLineArray[i + 2 * scanline_width];
  68961. d = scanLineArray[i + 3 * scanline_width];
  68962. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  68963. }
  68964. num_scanlines--;
  68965. }
  68966. return resultArray;
  68967. };
  68968. return HDRTools;
  68969. }());
  68970. BABYLON.HDRTools = HDRTools;
  68971. })(BABYLON || (BABYLON = {}));
  68972. //# sourceMappingURL=babylon.hdr.js.map
  68973. var BABYLON;
  68974. (function (BABYLON) {
  68975. /**
  68976. * This represents a texture coming from an HDR input.
  68977. *
  68978. * The only supported format is currently panorama picture stored in RGBE format.
  68979. * Example of such files can be found on HDRLib: http://hdrlib.com/
  68980. */
  68981. var HDRCubeTexture = /** @class */ (function (_super) {
  68982. __extends(HDRCubeTexture, _super);
  68983. /**
  68984. * Instantiates an HDRTexture from the following parameters.
  68985. *
  68986. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  68987. * @param scene The scene the texture will be used in
  68988. * @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.
  68989. * @param noMipmap Forces to not generate the mipmap if true
  68990. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  68991. * @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)
  68992. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  68993. */
  68994. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  68995. if (noMipmap === void 0) { noMipmap = false; }
  68996. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68997. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68998. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68999. if (onLoad === void 0) { onLoad = null; }
  69000. if (onError === void 0) { onError = null; }
  69001. var _this = _super.call(this, scene) || this;
  69002. _this._useInGammaSpace = false;
  69003. _this._generateHarmonics = true;
  69004. _this._isBABYLONPreprocessed = false;
  69005. _this._onLoad = null;
  69006. _this._onError = null;
  69007. /**
  69008. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  69009. */
  69010. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69011. /**
  69012. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  69013. * This is usefull at run time to apply the good shader.
  69014. */
  69015. _this.isPMREM = false;
  69016. _this._isBlocking = true;
  69017. if (!url) {
  69018. return _this;
  69019. }
  69020. _this.name = url;
  69021. _this.url = url;
  69022. _this.hasAlpha = false;
  69023. _this.isCube = true;
  69024. _this._textureMatrix = BABYLON.Matrix.Identity();
  69025. _this._onLoad = onLoad;
  69026. _this._onError = onError;
  69027. _this.gammaSpace = false;
  69028. var caps = scene.getEngine().getCaps();
  69029. if (size) {
  69030. _this._isBABYLONPreprocessed = false;
  69031. _this._noMipmap = noMipmap;
  69032. _this._size = size;
  69033. _this._useInGammaSpace = useInGammaSpace;
  69034. _this._usePMREMGenerator = usePMREMGenerator &&
  69035. caps.textureLOD &&
  69036. caps.textureFloat &&
  69037. !_this._useInGammaSpace;
  69038. }
  69039. else {
  69040. _this._isBABYLONPreprocessed = true;
  69041. _this._noMipmap = false;
  69042. _this._useInGammaSpace = false;
  69043. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  69044. !_this._useInGammaSpace;
  69045. }
  69046. _this.isPMREM = _this._usePMREMGenerator;
  69047. _this._texture = _this._getFromCache(url, _this._noMipmap);
  69048. if (!_this._texture) {
  69049. if (!scene.useDelayedTextureLoading) {
  69050. _this.loadTexture();
  69051. }
  69052. else {
  69053. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69054. }
  69055. }
  69056. return _this;
  69057. }
  69058. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  69059. /**
  69060. * Gets wether or not the texture is blocking during loading.
  69061. */
  69062. get: function () {
  69063. return this._isBlocking;
  69064. },
  69065. /**
  69066. * Sets wether or not the texture is blocking during loading.
  69067. */
  69068. set: function (value) {
  69069. this._isBlocking = value;
  69070. },
  69071. enumerable: true,
  69072. configurable: true
  69073. });
  69074. /**
  69075. * Occurs when the file is a preprocessed .babylon.hdr file.
  69076. */
  69077. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  69078. var _this = this;
  69079. var mipLevels = 0;
  69080. var floatArrayView = null;
  69081. var scene = this.getScene();
  69082. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  69083. var mips = new Array();
  69084. if (!floatArrayView) {
  69085. return mips;
  69086. }
  69087. var startIndex = 30;
  69088. for (var level = 0; level < mipLevels; level++) {
  69089. mips.push([]);
  69090. // Fill each pixel of the mip level.
  69091. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  69092. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69093. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  69094. mips[level].push(faceData);
  69095. startIndex += faceSize;
  69096. }
  69097. }
  69098. return mips;
  69099. } : null;
  69100. var callback = function (buffer) {
  69101. var scene = _this.getScene();
  69102. if (!scene) {
  69103. return null;
  69104. }
  69105. // Create Native Array Views
  69106. var intArrayView = new Int32Array(buffer);
  69107. floatArrayView = new Float32Array(buffer);
  69108. // Fill header.
  69109. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  69110. _this._size = intArrayView[1]; // CubeMap max mip face size.
  69111. // Update Texture Information.
  69112. if (!_this._texture) {
  69113. return null;
  69114. }
  69115. _this._texture.updateSize(_this._size, _this._size);
  69116. // Fill polynomial information.
  69117. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  69118. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  69119. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  69120. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  69121. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  69122. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  69123. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  69124. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  69125. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  69126. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  69127. _this.sphericalPolynomial = sphericalPolynomial;
  69128. // Fill pixel data.
  69129. mipLevels = intArrayView[29]; // Number of mip levels.
  69130. var startIndex = 30;
  69131. var data = [];
  69132. var faceSize = Math.pow(_this._size, 2) * 3;
  69133. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69134. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  69135. startIndex += faceSize;
  69136. }
  69137. var results = [];
  69138. var byteArray = null;
  69139. // Push each faces.
  69140. for (var k = 0; k < 6; k++) {
  69141. var dataFace = null;
  69142. // To be deprecated.
  69143. if (version === 1) {
  69144. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  69145. dataFace = data[j];
  69146. }
  69147. // If special cases.
  69148. if (!mipmapGenerator && dataFace) {
  69149. if (!scene.getEngine().getCaps().textureFloat) {
  69150. // 3 channels of 1 bytes per pixel in bytes.
  69151. var byteBuffer = new ArrayBuffer(faceSize);
  69152. byteArray = new Uint8Array(byteBuffer);
  69153. }
  69154. for (var i = 0; i < _this._size * _this._size; i++) {
  69155. // Put in gamma space if requested.
  69156. if (_this._useInGammaSpace) {
  69157. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69158. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69159. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69160. }
  69161. // Convert to int texture for fallback.
  69162. if (byteArray) {
  69163. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69164. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69165. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69166. // May use luminance instead if the result is not accurate.
  69167. var max = Math.max(Math.max(r, g), b);
  69168. if (max > 255) {
  69169. var scale = 255 / max;
  69170. r *= scale;
  69171. g *= scale;
  69172. b *= scale;
  69173. }
  69174. byteArray[(i * 3) + 0] = r;
  69175. byteArray[(i * 3) + 1] = g;
  69176. byteArray[(i * 3) + 2] = b;
  69177. }
  69178. }
  69179. }
  69180. // Fill the array accordingly.
  69181. if (byteArray) {
  69182. results.push(byteArray);
  69183. }
  69184. else {
  69185. results.push(dataFace);
  69186. }
  69187. }
  69188. return results;
  69189. };
  69190. if (scene) {
  69191. 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);
  69192. }
  69193. };
  69194. /**
  69195. * Occurs when the file is raw .hdr file.
  69196. */
  69197. HDRCubeTexture.prototype.loadHDRTexture = function () {
  69198. var _this = this;
  69199. var callback = function (buffer) {
  69200. var scene = _this.getScene();
  69201. if (!scene) {
  69202. return null;
  69203. }
  69204. // Extract the raw linear data.
  69205. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  69206. // Generate harmonics if needed.
  69207. if (_this._generateHarmonics) {
  69208. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  69209. _this.sphericalPolynomial = sphericalPolynomial;
  69210. }
  69211. var results = [];
  69212. var byteArray = null;
  69213. // Push each faces.
  69214. for (var j = 0; j < 6; j++) {
  69215. // Create uintarray fallback.
  69216. if (!scene.getEngine().getCaps().textureFloat) {
  69217. // 3 channels of 1 bytes per pixel in bytes.
  69218. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  69219. byteArray = new Uint8Array(byteBuffer);
  69220. }
  69221. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  69222. // If special cases.
  69223. if (_this._useInGammaSpace || byteArray) {
  69224. for (var i = 0; i < _this._size * _this._size; i++) {
  69225. // Put in gamma space if requested.
  69226. if (_this._useInGammaSpace) {
  69227. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69228. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69229. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69230. }
  69231. // Convert to int texture for fallback.
  69232. if (byteArray) {
  69233. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69234. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69235. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69236. // May use luminance instead if the result is not accurate.
  69237. var max = Math.max(Math.max(r, g), b);
  69238. if (max > 255) {
  69239. var scale = 255 / max;
  69240. r *= scale;
  69241. g *= scale;
  69242. b *= scale;
  69243. }
  69244. byteArray[(i * 3) + 0] = r;
  69245. byteArray[(i * 3) + 1] = g;
  69246. byteArray[(i * 3) + 2] = b;
  69247. }
  69248. }
  69249. }
  69250. if (byteArray) {
  69251. results.push(byteArray);
  69252. }
  69253. else {
  69254. results.push(dataFace);
  69255. }
  69256. }
  69257. return results;
  69258. };
  69259. var mipmapGenerator = null;
  69260. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  69261. // if (!this._noMipmap &&
  69262. // this._usePMREMGenerator) {
  69263. // mipmapGenerator = (data: ArrayBufferView[]) => {
  69264. // // Custom setup of the generator matching with the PBR shader values.
  69265. // var generator = new BABYLON.PMREMGenerator(data,
  69266. // this._size,
  69267. // this._size,
  69268. // 0,
  69269. // 3,
  69270. // this.getScene().getEngine().getCaps().textureFloat,
  69271. // 2048,
  69272. // 0.25,
  69273. // false,
  69274. // true);
  69275. // return generator.filterCubeMap();
  69276. // };
  69277. // }
  69278. var scene = this.getScene();
  69279. if (scene) {
  69280. 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);
  69281. }
  69282. };
  69283. /**
  69284. * Starts the loading process of the texture.
  69285. */
  69286. HDRCubeTexture.prototype.loadTexture = function () {
  69287. if (this._isBABYLONPreprocessed) {
  69288. this.loadBabylonTexture();
  69289. }
  69290. else {
  69291. this.loadHDRTexture();
  69292. }
  69293. };
  69294. HDRCubeTexture.prototype.clone = function () {
  69295. var scene = this.getScene();
  69296. if (!scene) {
  69297. return this;
  69298. }
  69299. var size = (this._isBABYLONPreprocessed ? null : this._size);
  69300. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  69301. // Base texture
  69302. newTexture.level = this.level;
  69303. newTexture.wrapU = this.wrapU;
  69304. newTexture.wrapV = this.wrapV;
  69305. newTexture.coordinatesIndex = this.coordinatesIndex;
  69306. newTexture.coordinatesMode = this.coordinatesMode;
  69307. return newTexture;
  69308. };
  69309. // Methods
  69310. HDRCubeTexture.prototype.delayLoad = function () {
  69311. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69312. return;
  69313. }
  69314. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69315. this._texture = this._getFromCache(this.url, this._noMipmap);
  69316. if (!this._texture) {
  69317. this.loadTexture();
  69318. }
  69319. };
  69320. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  69321. return this._textureMatrix;
  69322. };
  69323. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69324. this._textureMatrix = value;
  69325. };
  69326. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69327. var texture = null;
  69328. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  69329. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  69330. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  69331. texture.name = parsedTexture.name;
  69332. texture.hasAlpha = parsedTexture.hasAlpha;
  69333. texture.level = parsedTexture.level;
  69334. texture.coordinatesMode = parsedTexture.coordinatesMode;
  69335. texture.isBlocking = parsedTexture.isBlocking;
  69336. }
  69337. return texture;
  69338. };
  69339. HDRCubeTexture.prototype.serialize = function () {
  69340. if (!this.name) {
  69341. return null;
  69342. }
  69343. var serializationObject = {};
  69344. serializationObject.name = this.name;
  69345. serializationObject.hasAlpha = this.hasAlpha;
  69346. serializationObject.isCube = true;
  69347. serializationObject.level = this.level;
  69348. serializationObject.size = this._size;
  69349. serializationObject.coordinatesMode = this.coordinatesMode;
  69350. serializationObject.useInGammaSpace = this._useInGammaSpace;
  69351. serializationObject.generateHarmonics = this._generateHarmonics;
  69352. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  69353. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  69354. serializationObject.customType = "BABYLON.HDRCubeTexture";
  69355. serializationObject.noMipmap = this._noMipmap;
  69356. serializationObject.isBlocking = this._isBlocking;
  69357. return serializationObject;
  69358. };
  69359. /**
  69360. * Saves as a file the data contained in the texture in a binary format.
  69361. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69362. * as the spherical used in the lighting.
  69363. * @param url The HDR file url.
  69364. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69365. * @param onError Method called if any error happens during download.
  69366. * @return The packed binary data.
  69367. */
  69368. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  69369. if (onError === void 0) { onError = null; }
  69370. var callback = function (buffer) {
  69371. var data = new Blob([buffer], { type: 'application/octet-stream' });
  69372. // Returns a URL you can use as a href.
  69373. var objUrl = window.URL.createObjectURL(data);
  69374. // Simulates a link to it and click to dowload.
  69375. var a = document.createElement("a");
  69376. document.body.appendChild(a);
  69377. a.style.display = "none";
  69378. a.href = objUrl;
  69379. a.download = "envmap.babylon.hdr";
  69380. a.click();
  69381. };
  69382. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  69383. };
  69384. /**
  69385. * Serializes the data contained in the texture in a binary format.
  69386. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69387. * as the spherical used in the lighting.
  69388. * @param url The HDR file url.
  69389. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69390. * @param onError Method called if any error happens during download.
  69391. * @return The packed binary data.
  69392. */
  69393. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  69394. if (onError === void 0) { onError = null; }
  69395. // Needs the url tho create the texture.
  69396. if (!url) {
  69397. return;
  69398. }
  69399. // Check Power of two size.
  69400. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  69401. return;
  69402. }
  69403. // Coming Back in 3.x.
  69404. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  69405. };
  69406. HDRCubeTexture._facesMapping = [
  69407. "right",
  69408. "left",
  69409. "up",
  69410. "down",
  69411. "front",
  69412. "back"
  69413. ];
  69414. return HDRCubeTexture;
  69415. }(BABYLON.BaseTexture));
  69416. BABYLON.HDRCubeTexture = HDRCubeTexture;
  69417. })(BABYLON || (BABYLON = {}));
  69418. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  69419. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  69420. // Huge respect for a such great lib.
  69421. // Earcut license:
  69422. // Copyright (c) 2016, Mapbox
  69423. //
  69424. // Permission to use, copy, modify, and/or distribute this software for any purpose
  69425. // with or without fee is hereby granted, provided that the above copyright notice
  69426. // and this permission notice appear in all copies.
  69427. //
  69428. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  69429. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  69430. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  69431. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  69432. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  69433. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  69434. // THIS SOFTWARE.
  69435. var Earcut;
  69436. (function (Earcut) {
  69437. /**
  69438. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  69439. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  69440. * @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).
  69441. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  69442. */
  69443. function earcut(data, holeIndices, dim) {
  69444. dim = dim || 2;
  69445. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  69446. if (!outerNode)
  69447. return triangles;
  69448. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  69449. if (hasHoles)
  69450. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  69451. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  69452. if (data.length > 80 * dim) {
  69453. minX = maxX = data[0];
  69454. minY = maxY = data[1];
  69455. for (var i = dim; i < outerLen; i += dim) {
  69456. x = data[i];
  69457. y = data[i + 1];
  69458. if (x < minX)
  69459. minX = x;
  69460. if (y < minY)
  69461. minY = y;
  69462. if (x > maxX)
  69463. maxX = x;
  69464. if (y > maxY)
  69465. maxY = y;
  69466. }
  69467. // minX, minY and size are later used to transform coords into integers for z-order calculation
  69468. size = Math.max(maxX - minX, maxY - minY);
  69469. }
  69470. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  69471. return triangles;
  69472. }
  69473. Earcut.earcut = earcut;
  69474. var Node = /** @class */ (function () {
  69475. function Node(i, x, y) {
  69476. this.i = i;
  69477. this.x = x;
  69478. this.y = y;
  69479. this.prev = null;
  69480. this.next = null;
  69481. this.z = null;
  69482. this.prevZ = null;
  69483. this.nextZ = null;
  69484. this.steiner = false;
  69485. }
  69486. return Node;
  69487. }());
  69488. // create a circular doubly linked list from polygon points in the specified winding order
  69489. function linkedList(data, start, end, dim, clockwise) {
  69490. var i, last = null;
  69491. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  69492. for (i = start; i < end; i += dim)
  69493. last = insertNode(i, data[i], data[i + 1], last);
  69494. }
  69495. else {
  69496. for (i = end - dim; i >= start; i -= dim)
  69497. last = insertNode(i, data[i], data[i + 1], last);
  69498. }
  69499. if (last && equals(last, last.next)) {
  69500. removeNode(last);
  69501. last = last.next;
  69502. }
  69503. return last;
  69504. }
  69505. // eliminate colinear or duplicate points
  69506. function filterPoints(start, end) {
  69507. if (!start)
  69508. return start;
  69509. if (!end)
  69510. end = start;
  69511. var p = start, again;
  69512. do {
  69513. again = false;
  69514. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  69515. removeNode(p);
  69516. p = end = p.prev;
  69517. if (p === p.next)
  69518. return undefined;
  69519. again = true;
  69520. }
  69521. else {
  69522. p = p.next;
  69523. }
  69524. } while (again || p !== end);
  69525. return end;
  69526. }
  69527. // main ear slicing loop which triangulates a polygon (given as a linked list)
  69528. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  69529. if (!ear)
  69530. return;
  69531. // interlink polygon nodes in z-order
  69532. if (!pass && size)
  69533. indexCurve(ear, minX, minY, size);
  69534. var stop = ear, prev, next;
  69535. // iterate through ears, slicing them one by one
  69536. while (ear.prev !== ear.next) {
  69537. prev = ear.prev;
  69538. next = ear.next;
  69539. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  69540. // cut off the triangle
  69541. triangles.push(prev.i / dim);
  69542. triangles.push(ear.i / dim);
  69543. triangles.push(next.i / dim);
  69544. removeNode(ear);
  69545. // skipping the next vertice leads to less sliver triangles
  69546. ear = next.next;
  69547. stop = next.next;
  69548. continue;
  69549. }
  69550. ear = next;
  69551. // if we looped through the whole remaining polygon and can't find any more ears
  69552. if (ear === stop) {
  69553. // try filtering points and slicing again
  69554. if (!pass) {
  69555. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  69556. // if this didn't work, try curing all small self-intersections locally
  69557. }
  69558. else if (pass === 1) {
  69559. ear = cureLocalIntersections(ear, triangles, dim);
  69560. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  69561. // as a last resort, try splitting the remaining polygon into two
  69562. }
  69563. else if (pass === 2) {
  69564. splitEarcut(ear, triangles, dim, minX, minY, size);
  69565. }
  69566. break;
  69567. }
  69568. }
  69569. }
  69570. // check whether a polygon node forms a valid ear with adjacent nodes
  69571. function isEar(ear) {
  69572. var a = ear.prev, b = ear, c = ear.next;
  69573. if (area(a, b, c) >= 0)
  69574. return false; // reflex, can't be an ear
  69575. // now make sure we don't have other points inside the potential ear
  69576. var p = ear.next.next;
  69577. while (p !== ear.prev) {
  69578. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69579. area(p.prev, p, p.next) >= 0)
  69580. return false;
  69581. p = p.next;
  69582. }
  69583. return true;
  69584. }
  69585. function isEarHashed(ear, minX, minY, size) {
  69586. var a = ear.prev, b = ear, c = ear.next;
  69587. if (area(a, b, c) >= 0)
  69588. return false; // reflex, can't be an ear
  69589. // triangle bbox; min & max are calculated like this for speed
  69590. 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);
  69591. // z-order range for the current triangle bbox;
  69592. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  69593. // first look for points inside the triangle in increasing z-order
  69594. var p = ear.nextZ;
  69595. while (p && p.z <= maxZ) {
  69596. if (p !== ear.prev &&
  69597. p !== ear.next &&
  69598. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69599. area(p.prev, p, p.next) >= 0)
  69600. return false;
  69601. p = p.nextZ;
  69602. }
  69603. // then look for points in decreasing z-order
  69604. p = ear.prevZ;
  69605. while (p && p.z >= minZ) {
  69606. if (p !== ear.prev &&
  69607. p !== ear.next &&
  69608. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69609. area(p.prev, p, p.next) >= 0)
  69610. return false;
  69611. p = p.prevZ;
  69612. }
  69613. return true;
  69614. }
  69615. // go through all polygon nodes and cure small local self-intersections
  69616. function cureLocalIntersections(start, triangles, dim) {
  69617. var p = start;
  69618. do {
  69619. var a = p.prev, b = p.next.next;
  69620. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  69621. triangles.push(a.i / dim);
  69622. triangles.push(p.i / dim);
  69623. triangles.push(b.i / dim);
  69624. // remove two nodes involved
  69625. removeNode(p);
  69626. removeNode(p.next);
  69627. p = start = b;
  69628. }
  69629. p = p.next;
  69630. } while (p !== start);
  69631. return p;
  69632. }
  69633. // try splitting polygon into two and triangulate them independently
  69634. function splitEarcut(start, triangles, dim, minX, minY, size) {
  69635. // look for a valid diagonal that divides the polygon into two
  69636. var a = start;
  69637. do {
  69638. var b = a.next.next;
  69639. while (b !== a.prev) {
  69640. if (a.i !== b.i && isValidDiagonal(a, b)) {
  69641. // split the polygon in two by the diagonal
  69642. var c = splitPolygon(a, b);
  69643. // filter colinear points around the cuts
  69644. a = filterPoints(a, a.next);
  69645. c = filterPoints(c, c.next);
  69646. // run earcut on each half
  69647. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  69648. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  69649. return;
  69650. }
  69651. b = b.next;
  69652. }
  69653. a = a.next;
  69654. } while (a !== start);
  69655. }
  69656. // link every hole into the outer loop, producing a single-ring polygon without holes
  69657. function eliminateHoles(data, holeIndices, outerNode, dim) {
  69658. var queue = [], i, len, start, end, list;
  69659. for (i = 0, len = holeIndices.length; i < len; i++) {
  69660. start = holeIndices[i] * dim;
  69661. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69662. list = linkedList(data, start, end, dim, false);
  69663. if (list === list.next)
  69664. list.steiner = true;
  69665. queue.push(getLeftmost(list));
  69666. }
  69667. queue.sort(compareX);
  69668. // process holes from left to right
  69669. for (i = 0; i < queue.length; i++) {
  69670. eliminateHole(queue[i], outerNode);
  69671. outerNode = filterPoints(outerNode, outerNode.next);
  69672. }
  69673. return outerNode;
  69674. }
  69675. function compareX(a, b) {
  69676. return a.x - b.x;
  69677. }
  69678. // find a bridge between vertices that connects hole with an outer ring and and link it
  69679. function eliminateHole(hole, outerNode) {
  69680. outerNode = findHoleBridge(hole, outerNode);
  69681. if (outerNode) {
  69682. var b = splitPolygon(outerNode, hole);
  69683. filterPoints(b, b.next);
  69684. }
  69685. }
  69686. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  69687. function findHoleBridge(hole, outerNode) {
  69688. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  69689. // find a segment intersected by a ray from the hole's leftmost point to the left;
  69690. // segment's endpoint with lesser x will be potential connection point
  69691. do {
  69692. if (hy <= p.y && hy >= p.next.y) {
  69693. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  69694. if (x <= hx && x > qx) {
  69695. qx = x;
  69696. if (x === hx) {
  69697. if (hy === p.y)
  69698. return p;
  69699. if (hy === p.next.y)
  69700. return p.next;
  69701. }
  69702. m = p.x < p.next.x ? p : p.next;
  69703. }
  69704. }
  69705. p = p.next;
  69706. } while (p !== outerNode);
  69707. if (!m)
  69708. return null;
  69709. if (hx === qx)
  69710. return m.prev; // hole touches outer segment; pick lower endpoint
  69711. // look for points inside the triangle of hole point, segment intersection and endpoint;
  69712. // if there are no points found, we have a valid connection;
  69713. // otherwise choose the point of the minimum angle with the ray as connection point
  69714. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  69715. p = m.next;
  69716. while (p !== stop) {
  69717. if (hx >= p.x &&
  69718. p.x >= mx &&
  69719. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  69720. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  69721. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  69722. m = p;
  69723. tanMin = tan;
  69724. }
  69725. }
  69726. p = p.next;
  69727. }
  69728. return m;
  69729. }
  69730. // interlink polygon nodes in z-order
  69731. function indexCurve(start, minX, minY, size) {
  69732. var p = start;
  69733. do {
  69734. if (p.z === null)
  69735. p.z = zOrder(p.x, p.y, minX, minY, size);
  69736. p.prevZ = p.prev;
  69737. p.nextZ = p.next;
  69738. p = p.next;
  69739. } while (p !== start);
  69740. p.prevZ.nextZ = null;
  69741. p.prevZ = null;
  69742. sortLinked(p);
  69743. }
  69744. // Simon Tatham's linked list merge sort algorithm
  69745. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  69746. function sortLinked(list) {
  69747. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  69748. do {
  69749. p = list;
  69750. list = null;
  69751. tail = null;
  69752. numMerges = 0;
  69753. while (p) {
  69754. numMerges++;
  69755. q = p;
  69756. pSize = 0;
  69757. for (i = 0; i < inSize; i++) {
  69758. pSize++;
  69759. q = q.nextZ;
  69760. if (!q)
  69761. break;
  69762. }
  69763. qSize = inSize;
  69764. while (pSize > 0 || (qSize > 0 && q)) {
  69765. if (pSize === 0) {
  69766. e = q;
  69767. q = q.nextZ;
  69768. qSize--;
  69769. }
  69770. else if (qSize === 0 || !q) {
  69771. e = p;
  69772. p = p.nextZ;
  69773. pSize--;
  69774. }
  69775. else if (p.z <= q.z) {
  69776. e = p;
  69777. p = p.nextZ;
  69778. pSize--;
  69779. }
  69780. else {
  69781. e = q;
  69782. q = q.nextZ;
  69783. qSize--;
  69784. }
  69785. if (tail)
  69786. tail.nextZ = e;
  69787. else
  69788. list = e;
  69789. e.prevZ = tail;
  69790. tail = e;
  69791. }
  69792. p = q;
  69793. }
  69794. tail.nextZ = null;
  69795. inSize *= 2;
  69796. } while (numMerges > 1);
  69797. return list;
  69798. }
  69799. // z-order of a point given coords and size of the data bounding box
  69800. function zOrder(x, y, minX, minY, size) {
  69801. // coords are transformed into non-negative 15-bit integer range
  69802. x = 32767 * (x - minX) / size;
  69803. y = 32767 * (y - minY) / size;
  69804. x = (x | (x << 8)) & 0x00FF00FF;
  69805. x = (x | (x << 4)) & 0x0F0F0F0F;
  69806. x = (x | (x << 2)) & 0x33333333;
  69807. x = (x | (x << 1)) & 0x55555555;
  69808. y = (y | (y << 8)) & 0x00FF00FF;
  69809. y = (y | (y << 4)) & 0x0F0F0F0F;
  69810. y = (y | (y << 2)) & 0x33333333;
  69811. y = (y | (y << 1)) & 0x55555555;
  69812. return x | (y << 1);
  69813. }
  69814. // find the leftmost node of a polygon ring
  69815. function getLeftmost(start) {
  69816. var p = start, leftmost = start;
  69817. do {
  69818. if (p.x < leftmost.x)
  69819. leftmost = p;
  69820. p = p.next;
  69821. } while (p !== start);
  69822. return leftmost;
  69823. }
  69824. // check if a point lies within a convex triangle
  69825. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  69826. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  69827. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  69828. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  69829. }
  69830. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  69831. function isValidDiagonal(a, b) {
  69832. return a.next.i !== b.i &&
  69833. a.prev.i !== b.i &&
  69834. !intersectsPolygon(a, b) &&
  69835. locallyInside(a, b) &&
  69836. locallyInside(b, a) &&
  69837. middleInside(a, b);
  69838. }
  69839. // signed area of a triangle
  69840. function area(p, q, r) {
  69841. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  69842. }
  69843. // check if two points are equal
  69844. function equals(p1, p2) {
  69845. return p1.x === p2.x && p1.y === p2.y;
  69846. }
  69847. // check if two segments intersect
  69848. function intersects(p1, q1, p2, q2) {
  69849. if ((equals(p1, q1) && equals(p2, q2)) ||
  69850. (equals(p1, q2) && equals(p2, q1)))
  69851. return true;
  69852. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  69853. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  69854. }
  69855. // check if a polygon diagonal intersects any polygon segments
  69856. function intersectsPolygon(a, b) {
  69857. var p = a;
  69858. do {
  69859. if (p.i !== a.i &&
  69860. p.next.i !== a.i &&
  69861. p.i !== b.i &&
  69862. p.next.i !== b.i &&
  69863. intersects(p, p.next, a, b))
  69864. return true;
  69865. p = p.next;
  69866. } while (p !== a);
  69867. return false;
  69868. }
  69869. // check if a polygon diagonal is locally inside the polygon
  69870. function locallyInside(a, b) {
  69871. return area(a.prev, a, a.next) < 0
  69872. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  69873. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  69874. }
  69875. // check if the middle point of a polygon diagonal is inside the polygon
  69876. function middleInside(a, b) {
  69877. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  69878. do {
  69879. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  69880. inside = !inside;
  69881. p = p.next;
  69882. } while (p !== a);
  69883. return inside;
  69884. }
  69885. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  69886. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  69887. function splitPolygon(a, b) {
  69888. 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;
  69889. a.next = b;
  69890. b.prev = a;
  69891. a2.next = an;
  69892. an.prev = a2;
  69893. b2.next = a2;
  69894. a2.prev = b2;
  69895. bp.next = b2;
  69896. b2.prev = bp;
  69897. return b2;
  69898. }
  69899. // create a node and optionally link it with previous one (in a circular doubly linked list)
  69900. function insertNode(i, x, y, last) {
  69901. var p = new Node(i, x, y);
  69902. if (!last) {
  69903. p.prev = p;
  69904. p.next = p;
  69905. }
  69906. else {
  69907. p.next = last.next;
  69908. p.prev = last;
  69909. last.next.prev = p;
  69910. last.next = p;
  69911. }
  69912. return p;
  69913. }
  69914. function removeNode(p) {
  69915. p.next.prev = p.prev;
  69916. p.prev.next = p.next;
  69917. if (p.prevZ)
  69918. p.prevZ.nextZ = p.nextZ;
  69919. if (p.nextZ)
  69920. p.nextZ.prevZ = p.prevZ;
  69921. }
  69922. /**
  69923. * return a percentage difference between the polygon area and its triangulation area;
  69924. * used to verify correctness of triangulation
  69925. */
  69926. function deviation(data, holeIndices, dim, triangles) {
  69927. var hasHoles = holeIndices && holeIndices.length;
  69928. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  69929. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  69930. if (hasHoles) {
  69931. for (var i = 0, len = holeIndices.length; i < len; i++) {
  69932. var start = holeIndices[i] * dim;
  69933. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69934. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  69935. }
  69936. }
  69937. var trianglesArea = 0;
  69938. for (i = 0; i < triangles.length; i += 3) {
  69939. var a = triangles[i] * dim;
  69940. var b = triangles[i + 1] * dim;
  69941. var c = triangles[i + 2] * dim;
  69942. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  69943. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  69944. }
  69945. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  69946. }
  69947. Earcut.deviation = deviation;
  69948. ;
  69949. function signedArea(data, start, end, dim) {
  69950. var sum = 0;
  69951. for (var i = start, j = end - dim; i < end; i += dim) {
  69952. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  69953. j = i;
  69954. }
  69955. return sum;
  69956. }
  69957. /**
  69958. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  69959. */
  69960. function flatten(data) {
  69961. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  69962. for (var i = 0; i < data.length; i++) {
  69963. for (var j = 0; j < data[i].length; j++) {
  69964. for (var d = 0; d < dim; d++)
  69965. result.vertices.push(data[i][j][d]);
  69966. }
  69967. if (i > 0) {
  69968. holeIndex += data[i - 1].length;
  69969. result.holes.push(holeIndex);
  69970. }
  69971. }
  69972. return result;
  69973. }
  69974. Earcut.flatten = flatten;
  69975. ;
  69976. })(Earcut || (Earcut = {}));
  69977. //# sourceMappingURL=babylon.earcut.js.map
  69978. var BABYLON;
  69979. (function (BABYLON) {
  69980. var IndexedVector2 = /** @class */ (function (_super) {
  69981. __extends(IndexedVector2, _super);
  69982. function IndexedVector2(original, index) {
  69983. var _this = _super.call(this, original.x, original.y) || this;
  69984. _this.index = index;
  69985. return _this;
  69986. }
  69987. return IndexedVector2;
  69988. }(BABYLON.Vector2));
  69989. var PolygonPoints = /** @class */ (function () {
  69990. function PolygonPoints() {
  69991. this.elements = new Array();
  69992. }
  69993. PolygonPoints.prototype.add = function (originalPoints) {
  69994. var _this = this;
  69995. var result = new Array();
  69996. originalPoints.forEach(function (point) {
  69997. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  69998. var newPoint = new IndexedVector2(point, _this.elements.length);
  69999. result.push(newPoint);
  70000. _this.elements.push(newPoint);
  70001. }
  70002. });
  70003. return result;
  70004. };
  70005. PolygonPoints.prototype.computeBounds = function () {
  70006. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70007. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70008. this.elements.forEach(function (point) {
  70009. // x
  70010. if (point.x < lmin.x) {
  70011. lmin.x = point.x;
  70012. }
  70013. else if (point.x > lmax.x) {
  70014. lmax.x = point.x;
  70015. }
  70016. // y
  70017. if (point.y < lmin.y) {
  70018. lmin.y = point.y;
  70019. }
  70020. else if (point.y > lmax.y) {
  70021. lmax.y = point.y;
  70022. }
  70023. });
  70024. return {
  70025. min: lmin,
  70026. max: lmax,
  70027. width: lmax.x - lmin.x,
  70028. height: lmax.y - lmin.y
  70029. };
  70030. };
  70031. return PolygonPoints;
  70032. }());
  70033. var Polygon = /** @class */ (function () {
  70034. function Polygon() {
  70035. }
  70036. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  70037. return [
  70038. new BABYLON.Vector2(xmin, ymin),
  70039. new BABYLON.Vector2(xmax, ymin),
  70040. new BABYLON.Vector2(xmax, ymax),
  70041. new BABYLON.Vector2(xmin, ymax)
  70042. ];
  70043. };
  70044. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  70045. if (cx === void 0) { cx = 0; }
  70046. if (cy === void 0) { cy = 0; }
  70047. if (numberOfSides === void 0) { numberOfSides = 32; }
  70048. var result = new Array();
  70049. var angle = 0;
  70050. var increment = (Math.PI * 2) / numberOfSides;
  70051. for (var i = 0; i < numberOfSides; i++) {
  70052. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  70053. angle -= increment;
  70054. }
  70055. return result;
  70056. };
  70057. Polygon.Parse = function (input) {
  70058. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  70059. var i, result = [];
  70060. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  70061. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  70062. }
  70063. return result;
  70064. };
  70065. Polygon.StartingAt = function (x, y) {
  70066. return BABYLON.Path2.StartingAt(x, y);
  70067. };
  70068. return Polygon;
  70069. }());
  70070. BABYLON.Polygon = Polygon;
  70071. var PolygonMeshBuilder = /** @class */ (function () {
  70072. function PolygonMeshBuilder(name, contours, scene) {
  70073. this._points = new PolygonPoints();
  70074. this._outlinepoints = new PolygonPoints();
  70075. this._holes = new Array();
  70076. this._epoints = new Array();
  70077. this._eholes = new Array();
  70078. this._name = name;
  70079. this._scene = scene;
  70080. var points;
  70081. if (contours instanceof BABYLON.Path2) {
  70082. points = contours.getPoints();
  70083. }
  70084. else {
  70085. points = contours;
  70086. }
  70087. this._addToepoint(points);
  70088. this._points.add(points);
  70089. this._outlinepoints.add(points);
  70090. }
  70091. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  70092. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  70093. var p = points_1[_i];
  70094. this._epoints.push(p.x, p.y);
  70095. }
  70096. };
  70097. PolygonMeshBuilder.prototype.addHole = function (hole) {
  70098. this._points.add(hole);
  70099. var holepoints = new PolygonPoints();
  70100. holepoints.add(hole);
  70101. this._holes.push(holepoints);
  70102. this._eholes.push(this._epoints.length / 2);
  70103. this._addToepoint(hole);
  70104. return this;
  70105. };
  70106. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  70107. var _this = this;
  70108. if (updatable === void 0) { updatable = false; }
  70109. if (depth === void 0) { depth = 0; }
  70110. var result = new BABYLON.Mesh(this._name, this._scene);
  70111. var normals = new Array();
  70112. var positions = new Array();
  70113. var uvs = new Array();
  70114. var bounds = this._points.computeBounds();
  70115. this._points.elements.forEach(function (p) {
  70116. normals.push(0, 1.0, 0);
  70117. positions.push(p.x, 0, p.y);
  70118. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  70119. });
  70120. var indices = new Array();
  70121. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  70122. for (var i = 0; i < res.length; i++) {
  70123. indices.push(res[i]);
  70124. }
  70125. if (depth > 0) {
  70126. var positionscount = (positions.length / 3); //get the current pointcount
  70127. this._points.elements.forEach(function (p) {
  70128. normals.push(0, -1.0, 0);
  70129. positions.push(p.x, -depth, p.y);
  70130. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  70131. });
  70132. var totalCount = indices.length;
  70133. for (var i = 0; i < totalCount; i += 3) {
  70134. var i0 = indices[i + 0];
  70135. var i1 = indices[i + 1];
  70136. var i2 = indices[i + 2];
  70137. indices.push(i2 + positionscount);
  70138. indices.push(i1 + positionscount);
  70139. indices.push(i0 + positionscount);
  70140. }
  70141. //Add the sides
  70142. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  70143. this._holes.forEach(function (hole) {
  70144. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  70145. });
  70146. }
  70147. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  70148. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  70149. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  70150. result.setIndices(indices);
  70151. return result;
  70152. };
  70153. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  70154. var StartIndex = positions.length / 3;
  70155. var ulength = 0;
  70156. for (var i = 0; i < points.elements.length; i++) {
  70157. var p = points.elements[i];
  70158. var p1;
  70159. if ((i + 1) > points.elements.length - 1) {
  70160. p1 = points.elements[0];
  70161. }
  70162. else {
  70163. p1 = points.elements[i + 1];
  70164. }
  70165. positions.push(p.x, 0, p.y);
  70166. positions.push(p.x, -depth, p.y);
  70167. positions.push(p1.x, 0, p1.y);
  70168. positions.push(p1.x, -depth, p1.y);
  70169. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  70170. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  70171. var v3 = v2.subtract(v1);
  70172. var v4 = new BABYLON.Vector3(0, 1, 0);
  70173. var vn = BABYLON.Vector3.Cross(v3, v4);
  70174. vn = vn.normalize();
  70175. uvs.push(ulength / bounds.width, 0);
  70176. uvs.push(ulength / bounds.width, 1);
  70177. ulength += v3.length();
  70178. uvs.push((ulength / bounds.width), 0);
  70179. uvs.push((ulength / bounds.width), 1);
  70180. if (!flip) {
  70181. normals.push(-vn.x, -vn.y, -vn.z);
  70182. normals.push(-vn.x, -vn.y, -vn.z);
  70183. normals.push(-vn.x, -vn.y, -vn.z);
  70184. normals.push(-vn.x, -vn.y, -vn.z);
  70185. indices.push(StartIndex);
  70186. indices.push(StartIndex + 1);
  70187. indices.push(StartIndex + 2);
  70188. indices.push(StartIndex + 1);
  70189. indices.push(StartIndex + 3);
  70190. indices.push(StartIndex + 2);
  70191. }
  70192. else {
  70193. normals.push(vn.x, vn.y, vn.z);
  70194. normals.push(vn.x, vn.y, vn.z);
  70195. normals.push(vn.x, vn.y, vn.z);
  70196. normals.push(vn.x, vn.y, vn.z);
  70197. indices.push(StartIndex);
  70198. indices.push(StartIndex + 2);
  70199. indices.push(StartIndex + 1);
  70200. indices.push(StartIndex + 1);
  70201. indices.push(StartIndex + 2);
  70202. indices.push(StartIndex + 3);
  70203. }
  70204. StartIndex += 4;
  70205. }
  70206. ;
  70207. };
  70208. return PolygonMeshBuilder;
  70209. }());
  70210. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  70211. })(BABYLON || (BABYLON = {}));
  70212. //# sourceMappingURL=babylon.polygonMesh.js.map
  70213. var BABYLON;
  70214. (function (BABYLON) {
  70215. // Unique ID when we import meshes from Babylon to CSG
  70216. var currentCSGMeshId = 0;
  70217. // # class Vertex
  70218. // Represents a vertex of a polygon. Use your own vertex class instead of this
  70219. // one to provide additional features like texture coordinates and vertex
  70220. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  70221. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  70222. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  70223. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  70224. // is not used anywhere else.
  70225. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  70226. var Vertex = /** @class */ (function () {
  70227. function Vertex(pos, normal, uv) {
  70228. this.pos = pos;
  70229. this.normal = normal;
  70230. this.uv = uv;
  70231. }
  70232. Vertex.prototype.clone = function () {
  70233. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  70234. };
  70235. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  70236. // orientation of a polygon is flipped.
  70237. Vertex.prototype.flip = function () {
  70238. this.normal = this.normal.scale(-1);
  70239. };
  70240. // Create a new vertex between this vertex and `other` by linearly
  70241. // interpolating all properties using a parameter of `t`. Subclasses should
  70242. // override this to interpolate additional properties.
  70243. Vertex.prototype.interpolate = function (other, t) {
  70244. 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));
  70245. };
  70246. return Vertex;
  70247. }());
  70248. // # class Plane
  70249. // Represents a plane in 3D space.
  70250. var Plane = /** @class */ (function () {
  70251. function Plane(normal, w) {
  70252. this.normal = normal;
  70253. this.w = w;
  70254. }
  70255. Plane.FromPoints = function (a, b, c) {
  70256. var v0 = c.subtract(a);
  70257. var v1 = b.subtract(a);
  70258. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  70259. return null;
  70260. }
  70261. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  70262. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  70263. };
  70264. Plane.prototype.clone = function () {
  70265. return new Plane(this.normal.clone(), this.w);
  70266. };
  70267. Plane.prototype.flip = function () {
  70268. this.normal.scaleInPlace(-1);
  70269. this.w = -this.w;
  70270. };
  70271. // Split `polygon` by this plane if needed, then put the polygon or polygon
  70272. // fragments in the appropriate lists. Coplanar polygons go into either
  70273. // `coplanarFront` or `coplanarBack` depending on their orientation with
  70274. // respect to this plane. Polygons in front or in back of this plane go into
  70275. // either `front` or `back`.
  70276. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  70277. var COPLANAR = 0;
  70278. var FRONT = 1;
  70279. var BACK = 2;
  70280. var SPANNING = 3;
  70281. // Classify each point as well as the entire polygon into one of the above
  70282. // four classes.
  70283. var polygonType = 0;
  70284. var types = [];
  70285. var i;
  70286. var t;
  70287. for (i = 0; i < polygon.vertices.length; i++) {
  70288. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  70289. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  70290. polygonType |= type;
  70291. types.push(type);
  70292. }
  70293. // Put the polygon in the correct list, splitting it when necessary.
  70294. switch (polygonType) {
  70295. case COPLANAR:
  70296. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  70297. break;
  70298. case FRONT:
  70299. front.push(polygon);
  70300. break;
  70301. case BACK:
  70302. back.push(polygon);
  70303. break;
  70304. case SPANNING:
  70305. var f = [], b = [];
  70306. for (i = 0; i < polygon.vertices.length; i++) {
  70307. var j = (i + 1) % polygon.vertices.length;
  70308. var ti = types[i], tj = types[j];
  70309. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  70310. if (ti !== BACK)
  70311. f.push(vi);
  70312. if (ti !== FRONT)
  70313. b.push(ti !== BACK ? vi.clone() : vi);
  70314. if ((ti | tj) === SPANNING) {
  70315. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  70316. var v = vi.interpolate(vj, t);
  70317. f.push(v);
  70318. b.push(v.clone());
  70319. }
  70320. }
  70321. var poly;
  70322. if (f.length >= 3) {
  70323. poly = new Polygon(f, polygon.shared);
  70324. if (poly.plane)
  70325. front.push(poly);
  70326. }
  70327. if (b.length >= 3) {
  70328. poly = new Polygon(b, polygon.shared);
  70329. if (poly.plane)
  70330. back.push(poly);
  70331. }
  70332. break;
  70333. }
  70334. };
  70335. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  70336. // point is on the plane.
  70337. Plane.EPSILON = 1e-5;
  70338. return Plane;
  70339. }());
  70340. // # class Polygon
  70341. // Represents a convex polygon. The vertices used to initialize a polygon must
  70342. // be coplanar and form a convex loop.
  70343. //
  70344. // Each convex polygon has a `shared` property, which is shared between all
  70345. // polygons that are clones of each other or were split from the same polygon.
  70346. // This can be used to define per-polygon properties (such as surface color).
  70347. var Polygon = /** @class */ (function () {
  70348. function Polygon(vertices, shared) {
  70349. this.vertices = vertices;
  70350. this.shared = shared;
  70351. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  70352. }
  70353. Polygon.prototype.clone = function () {
  70354. var vertices = this.vertices.map(function (v) { return v.clone(); });
  70355. return new Polygon(vertices, this.shared);
  70356. };
  70357. Polygon.prototype.flip = function () {
  70358. this.vertices.reverse().map(function (v) { v.flip(); });
  70359. this.plane.flip();
  70360. };
  70361. return Polygon;
  70362. }());
  70363. // # class Node
  70364. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  70365. // by picking a polygon to split along. That polygon (and all other coplanar
  70366. // polygons) are added directly to that node and the other polygons are added to
  70367. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  70368. // no distinction between internal and leaf nodes.
  70369. var Node = /** @class */ (function () {
  70370. function Node(polygons) {
  70371. this.plane = null;
  70372. this.front = null;
  70373. this.back = null;
  70374. this.polygons = new Array();
  70375. if (polygons) {
  70376. this.build(polygons);
  70377. }
  70378. }
  70379. Node.prototype.clone = function () {
  70380. var node = new Node();
  70381. node.plane = this.plane && this.plane.clone();
  70382. node.front = this.front && this.front.clone();
  70383. node.back = this.back && this.back.clone();
  70384. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  70385. return node;
  70386. };
  70387. // Convert solid space to empty space and empty space to solid space.
  70388. Node.prototype.invert = function () {
  70389. for (var i = 0; i < this.polygons.length; i++) {
  70390. this.polygons[i].flip();
  70391. }
  70392. if (this.plane) {
  70393. this.plane.flip();
  70394. }
  70395. if (this.front) {
  70396. this.front.invert();
  70397. }
  70398. if (this.back) {
  70399. this.back.invert();
  70400. }
  70401. var temp = this.front;
  70402. this.front = this.back;
  70403. this.back = temp;
  70404. };
  70405. // Recursively remove all polygons in `polygons` that are inside this BSP
  70406. // tree.
  70407. Node.prototype.clipPolygons = function (polygons) {
  70408. if (!this.plane)
  70409. return polygons.slice();
  70410. var front = new Array(), back = new Array();
  70411. for (var i = 0; i < polygons.length; i++) {
  70412. this.plane.splitPolygon(polygons[i], front, back, front, back);
  70413. }
  70414. if (this.front) {
  70415. front = this.front.clipPolygons(front);
  70416. }
  70417. if (this.back) {
  70418. back = this.back.clipPolygons(back);
  70419. }
  70420. else {
  70421. back = [];
  70422. }
  70423. return front.concat(back);
  70424. };
  70425. // Remove all polygons in this BSP tree that are inside the other BSP tree
  70426. // `bsp`.
  70427. Node.prototype.clipTo = function (bsp) {
  70428. this.polygons = bsp.clipPolygons(this.polygons);
  70429. if (this.front)
  70430. this.front.clipTo(bsp);
  70431. if (this.back)
  70432. this.back.clipTo(bsp);
  70433. };
  70434. // Return a list of all polygons in this BSP tree.
  70435. Node.prototype.allPolygons = function () {
  70436. var polygons = this.polygons.slice();
  70437. if (this.front)
  70438. polygons = polygons.concat(this.front.allPolygons());
  70439. if (this.back)
  70440. polygons = polygons.concat(this.back.allPolygons());
  70441. return polygons;
  70442. };
  70443. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  70444. // new polygons are filtered down to the bottom of the tree and become new
  70445. // nodes there. Each set of polygons is partitioned using the first polygon
  70446. // (no heuristic is used to pick a good split).
  70447. Node.prototype.build = function (polygons) {
  70448. if (!polygons.length)
  70449. return;
  70450. if (!this.plane)
  70451. this.plane = polygons[0].plane.clone();
  70452. var front = new Array(), back = new Array();
  70453. for (var i = 0; i < polygons.length; i++) {
  70454. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  70455. }
  70456. if (front.length) {
  70457. if (!this.front)
  70458. this.front = new Node();
  70459. this.front.build(front);
  70460. }
  70461. if (back.length) {
  70462. if (!this.back)
  70463. this.back = new Node();
  70464. this.back.build(back);
  70465. }
  70466. };
  70467. return Node;
  70468. }());
  70469. var CSG = /** @class */ (function () {
  70470. function CSG() {
  70471. this.polygons = new Array();
  70472. }
  70473. // Convert BABYLON.Mesh to BABYLON.CSG
  70474. CSG.FromMesh = function (mesh) {
  70475. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  70476. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  70477. if (mesh instanceof BABYLON.Mesh) {
  70478. mesh.computeWorldMatrix(true);
  70479. matrix = mesh.getWorldMatrix();
  70480. meshPosition = mesh.position.clone();
  70481. meshRotation = mesh.rotation.clone();
  70482. if (mesh.rotationQuaternion) {
  70483. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  70484. }
  70485. meshScaling = mesh.scaling.clone();
  70486. }
  70487. else {
  70488. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  70489. }
  70490. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70491. var subMeshes = mesh.subMeshes;
  70492. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  70493. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  70494. vertices = [];
  70495. for (var j = 0; j < 3; j++) {
  70496. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  70497. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  70498. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  70499. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  70500. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  70501. vertex = new Vertex(position, normal, uv);
  70502. vertices.push(vertex);
  70503. }
  70504. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  70505. // To handle the case of degenerated triangle
  70506. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  70507. if (polygon.plane)
  70508. polygons.push(polygon);
  70509. }
  70510. }
  70511. var csg = CSG.FromPolygons(polygons);
  70512. csg.matrix = matrix;
  70513. csg.position = meshPosition;
  70514. csg.rotation = meshRotation;
  70515. csg.scaling = meshScaling;
  70516. csg.rotationQuaternion = meshRotationQuaternion;
  70517. currentCSGMeshId++;
  70518. return csg;
  70519. };
  70520. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  70521. CSG.FromPolygons = function (polygons) {
  70522. var csg = new CSG();
  70523. csg.polygons = polygons;
  70524. return csg;
  70525. };
  70526. CSG.prototype.clone = function () {
  70527. var csg = new CSG();
  70528. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  70529. csg.copyTransformAttributes(this);
  70530. return csg;
  70531. };
  70532. CSG.prototype.union = function (csg) {
  70533. var a = new Node(this.clone().polygons);
  70534. var b = new Node(csg.clone().polygons);
  70535. a.clipTo(b);
  70536. b.clipTo(a);
  70537. b.invert();
  70538. b.clipTo(a);
  70539. b.invert();
  70540. a.build(b.allPolygons());
  70541. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70542. };
  70543. CSG.prototype.unionInPlace = function (csg) {
  70544. var a = new Node(this.polygons);
  70545. var b = new Node(csg.polygons);
  70546. a.clipTo(b);
  70547. b.clipTo(a);
  70548. b.invert();
  70549. b.clipTo(a);
  70550. b.invert();
  70551. a.build(b.allPolygons());
  70552. this.polygons = a.allPolygons();
  70553. };
  70554. CSG.prototype.subtract = function (csg) {
  70555. var a = new Node(this.clone().polygons);
  70556. var b = new Node(csg.clone().polygons);
  70557. a.invert();
  70558. a.clipTo(b);
  70559. b.clipTo(a);
  70560. b.invert();
  70561. b.clipTo(a);
  70562. b.invert();
  70563. a.build(b.allPolygons());
  70564. a.invert();
  70565. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70566. };
  70567. CSG.prototype.subtractInPlace = function (csg) {
  70568. var a = new Node(this.polygons);
  70569. var b = new Node(csg.polygons);
  70570. a.invert();
  70571. a.clipTo(b);
  70572. b.clipTo(a);
  70573. b.invert();
  70574. b.clipTo(a);
  70575. b.invert();
  70576. a.build(b.allPolygons());
  70577. a.invert();
  70578. this.polygons = a.allPolygons();
  70579. };
  70580. CSG.prototype.intersect = function (csg) {
  70581. var a = new Node(this.clone().polygons);
  70582. var b = new Node(csg.clone().polygons);
  70583. a.invert();
  70584. b.clipTo(a);
  70585. b.invert();
  70586. a.clipTo(b);
  70587. b.clipTo(a);
  70588. a.build(b.allPolygons());
  70589. a.invert();
  70590. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70591. };
  70592. CSG.prototype.intersectInPlace = function (csg) {
  70593. var a = new Node(this.polygons);
  70594. var b = new Node(csg.polygons);
  70595. a.invert();
  70596. b.clipTo(a);
  70597. b.invert();
  70598. a.clipTo(b);
  70599. b.clipTo(a);
  70600. a.build(b.allPolygons());
  70601. a.invert();
  70602. this.polygons = a.allPolygons();
  70603. };
  70604. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  70605. // not modified.
  70606. CSG.prototype.inverse = function () {
  70607. var csg = this.clone();
  70608. csg.inverseInPlace();
  70609. return csg;
  70610. };
  70611. CSG.prototype.inverseInPlace = function () {
  70612. this.polygons.map(function (p) { p.flip(); });
  70613. };
  70614. // This is used to keep meshes transformations so they can be restored
  70615. // when we build back a Babylon Mesh
  70616. // NB : All CSG operations are performed in world coordinates
  70617. CSG.prototype.copyTransformAttributes = function (csg) {
  70618. this.matrix = csg.matrix;
  70619. this.position = csg.position;
  70620. this.rotation = csg.rotation;
  70621. this.scaling = csg.scaling;
  70622. this.rotationQuaternion = csg.rotationQuaternion;
  70623. return this;
  70624. };
  70625. // Build Raw mesh from CSG
  70626. // Coordinates here are in world space
  70627. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  70628. var matrix = this.matrix.clone();
  70629. matrix.invert();
  70630. 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;
  70631. if (keepSubMeshes) {
  70632. // Sort Polygons, since subMeshes are indices range
  70633. polygons.sort(function (a, b) {
  70634. if (a.shared.meshId === b.shared.meshId) {
  70635. return a.shared.subMeshId - b.shared.subMeshId;
  70636. }
  70637. else {
  70638. return a.shared.meshId - b.shared.meshId;
  70639. }
  70640. });
  70641. }
  70642. for (var i = 0, il = polygons.length; i < il; i++) {
  70643. polygon = polygons[i];
  70644. // Building SubMeshes
  70645. if (!subMesh_dict[polygon.shared.meshId]) {
  70646. subMesh_dict[polygon.shared.meshId] = {};
  70647. }
  70648. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  70649. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  70650. indexStart: +Infinity,
  70651. indexEnd: -Infinity,
  70652. materialIndex: polygon.shared.materialIndex
  70653. };
  70654. }
  70655. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  70656. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  70657. polygonIndices[0] = 0;
  70658. polygonIndices[1] = j - 1;
  70659. polygonIndices[2] = j;
  70660. for (var k = 0; k < 3; k++) {
  70661. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  70662. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  70663. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  70664. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  70665. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  70666. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  70667. // Check if 2 points can be merged
  70668. if (!(typeof vertex_idx !== 'undefined' &&
  70669. normals[vertex_idx * 3] === localNormal.x &&
  70670. normals[vertex_idx * 3 + 1] === localNormal.y &&
  70671. normals[vertex_idx * 3 + 2] === localNormal.z &&
  70672. uvs[vertex_idx * 2] === uv.x &&
  70673. uvs[vertex_idx * 2 + 1] === uv.y)) {
  70674. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  70675. uvs.push(uv.x, uv.y);
  70676. normals.push(normal.x, normal.y, normal.z);
  70677. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  70678. }
  70679. indices.push(vertex_idx);
  70680. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  70681. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  70682. currentIndex++;
  70683. }
  70684. }
  70685. }
  70686. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  70687. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  70688. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  70689. mesh.setIndices(indices, null);
  70690. if (keepSubMeshes) {
  70691. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  70692. var materialIndexOffset = 0, materialMaxIndex;
  70693. mesh.subMeshes = new Array();
  70694. for (var m in subMesh_dict) {
  70695. materialMaxIndex = -1;
  70696. for (var sm in subMesh_dict[m]) {
  70697. subMesh_obj = subMesh_dict[m][sm];
  70698. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  70699. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  70700. }
  70701. materialIndexOffset += ++materialMaxIndex;
  70702. }
  70703. }
  70704. return mesh;
  70705. };
  70706. // Build Mesh from CSG taking material and transforms into account
  70707. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  70708. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  70709. mesh.material = material;
  70710. mesh.position.copyFrom(this.position);
  70711. mesh.rotation.copyFrom(this.rotation);
  70712. if (this.rotationQuaternion) {
  70713. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  70714. }
  70715. mesh.scaling.copyFrom(this.scaling);
  70716. mesh.computeWorldMatrix(true);
  70717. return mesh;
  70718. };
  70719. return CSG;
  70720. }());
  70721. BABYLON.CSG = CSG;
  70722. })(BABYLON || (BABYLON = {}));
  70723. //# sourceMappingURL=babylon.csg.js.map
  70724. var BABYLON;
  70725. (function (BABYLON) {
  70726. var LensFlare = /** @class */ (function () {
  70727. function LensFlare(size, position, color, imgUrl, system) {
  70728. this.size = size;
  70729. this.position = position;
  70730. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  70731. this.color = color || new BABYLON.Color3(1, 1, 1);
  70732. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  70733. this._system = system;
  70734. system.lensFlares.push(this);
  70735. }
  70736. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  70737. return new LensFlare(size, position, color, imgUrl, system);
  70738. };
  70739. LensFlare.prototype.dispose = function () {
  70740. if (this.texture) {
  70741. this.texture.dispose();
  70742. }
  70743. // Remove from scene
  70744. var index = this._system.lensFlares.indexOf(this);
  70745. this._system.lensFlares.splice(index, 1);
  70746. };
  70747. ;
  70748. return LensFlare;
  70749. }());
  70750. BABYLON.LensFlare = LensFlare;
  70751. })(BABYLON || (BABYLON = {}));
  70752. //# sourceMappingURL=babylon.lensFlare.js.map
  70753. var BABYLON;
  70754. (function (BABYLON) {
  70755. var LensFlareSystem = /** @class */ (function () {
  70756. function LensFlareSystem(name, emitter, scene) {
  70757. this.name = name;
  70758. this.lensFlares = new Array();
  70759. this.borderLimit = 300;
  70760. this.viewportBorder = 0;
  70761. this.layerMask = 0x0FFFFFFF;
  70762. this._vertexBuffers = {};
  70763. this._isEnabled = true;
  70764. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70765. this._emitter = emitter;
  70766. this.id = name;
  70767. scene.lensFlareSystems.push(this);
  70768. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  70769. var engine = scene.getEngine();
  70770. // VBO
  70771. var vertices = [];
  70772. vertices.push(1, 1);
  70773. vertices.push(-1, 1);
  70774. vertices.push(-1, -1);
  70775. vertices.push(1, -1);
  70776. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70777. // Indices
  70778. var indices = [];
  70779. indices.push(0);
  70780. indices.push(1);
  70781. indices.push(2);
  70782. indices.push(0);
  70783. indices.push(2);
  70784. indices.push(3);
  70785. this._indexBuffer = engine.createIndexBuffer(indices);
  70786. // Effects
  70787. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  70788. }
  70789. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  70790. get: function () {
  70791. return this._isEnabled;
  70792. },
  70793. set: function (value) {
  70794. this._isEnabled = value;
  70795. },
  70796. enumerable: true,
  70797. configurable: true
  70798. });
  70799. LensFlareSystem.prototype.getScene = function () {
  70800. return this._scene;
  70801. };
  70802. LensFlareSystem.prototype.getEmitter = function () {
  70803. return this._emitter;
  70804. };
  70805. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  70806. this._emitter = newEmitter;
  70807. };
  70808. LensFlareSystem.prototype.getEmitterPosition = function () {
  70809. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  70810. };
  70811. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  70812. var position = this.getEmitterPosition();
  70813. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  70814. this._positionX = position.x;
  70815. this._positionY = position.y;
  70816. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  70817. if (this.viewportBorder > 0) {
  70818. globalViewport.x -= this.viewportBorder;
  70819. globalViewport.y -= this.viewportBorder;
  70820. globalViewport.width += this.viewportBorder * 2;
  70821. globalViewport.height += this.viewportBorder * 2;
  70822. position.x += this.viewportBorder;
  70823. position.y += this.viewportBorder;
  70824. this._positionX += this.viewportBorder;
  70825. this._positionY += this.viewportBorder;
  70826. }
  70827. if (position.z > 0) {
  70828. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  70829. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  70830. return true;
  70831. }
  70832. return true;
  70833. }
  70834. return false;
  70835. };
  70836. LensFlareSystem.prototype._isVisible = function () {
  70837. if (!this._isEnabled || !this._scene.activeCamera) {
  70838. return false;
  70839. }
  70840. var emitterPosition = this.getEmitterPosition();
  70841. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  70842. var distance = direction.length();
  70843. direction.normalize();
  70844. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  70845. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  70846. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  70847. };
  70848. LensFlareSystem.prototype.render = function () {
  70849. if (!this._effect.isReady() || !this._scene.activeCamera)
  70850. return false;
  70851. var engine = this._scene.getEngine();
  70852. var viewport = this._scene.activeCamera.viewport;
  70853. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  70854. // Position
  70855. if (!this.computeEffectivePosition(globalViewport)) {
  70856. return false;
  70857. }
  70858. // Visibility
  70859. if (!this._isVisible()) {
  70860. return false;
  70861. }
  70862. // Intensity
  70863. var awayX;
  70864. var awayY;
  70865. if (this._positionX < this.borderLimit + globalViewport.x) {
  70866. awayX = this.borderLimit + globalViewport.x - this._positionX;
  70867. }
  70868. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  70869. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  70870. }
  70871. else {
  70872. awayX = 0;
  70873. }
  70874. if (this._positionY < this.borderLimit + globalViewport.y) {
  70875. awayY = this.borderLimit + globalViewport.y - this._positionY;
  70876. }
  70877. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  70878. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  70879. }
  70880. else {
  70881. awayY = 0;
  70882. }
  70883. var away = (awayX > awayY) ? awayX : awayY;
  70884. away -= this.viewportBorder;
  70885. if (away > this.borderLimit) {
  70886. away = this.borderLimit;
  70887. }
  70888. var intensity = 1.0 - (away / this.borderLimit);
  70889. if (intensity < 0) {
  70890. return false;
  70891. }
  70892. if (intensity > 1.0) {
  70893. intensity = 1.0;
  70894. }
  70895. if (this.viewportBorder > 0) {
  70896. globalViewport.x += this.viewportBorder;
  70897. globalViewport.y += this.viewportBorder;
  70898. globalViewport.width -= this.viewportBorder * 2;
  70899. globalViewport.height -= this.viewportBorder * 2;
  70900. this._positionX -= this.viewportBorder;
  70901. this._positionY -= this.viewportBorder;
  70902. }
  70903. // Position
  70904. var centerX = globalViewport.x + globalViewport.width / 2;
  70905. var centerY = globalViewport.y + globalViewport.height / 2;
  70906. var distX = centerX - this._positionX;
  70907. var distY = centerY - this._positionY;
  70908. // Effects
  70909. engine.enableEffect(this._effect);
  70910. engine.setState(false);
  70911. engine.setDepthBuffer(false);
  70912. // VBOs
  70913. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70914. // Flares
  70915. for (var index = 0; index < this.lensFlares.length; index++) {
  70916. var flare = this.lensFlares[index];
  70917. engine.setAlphaMode(flare.alphaMode);
  70918. var x = centerX - (distX * flare.position);
  70919. var y = centerY - (distY * flare.position);
  70920. var cw = flare.size;
  70921. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  70922. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  70923. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  70924. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  70925. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  70926. // Texture
  70927. this._effect.setTexture("textureSampler", flare.texture);
  70928. // Color
  70929. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  70930. // Draw order
  70931. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70932. }
  70933. engine.setDepthBuffer(true);
  70934. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70935. return true;
  70936. };
  70937. LensFlareSystem.prototype.dispose = function () {
  70938. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70939. if (vertexBuffer) {
  70940. vertexBuffer.dispose();
  70941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70942. }
  70943. if (this._indexBuffer) {
  70944. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70945. this._indexBuffer = null;
  70946. }
  70947. while (this.lensFlares.length) {
  70948. this.lensFlares[0].dispose();
  70949. }
  70950. // Remove from scene
  70951. var index = this._scene.lensFlareSystems.indexOf(this);
  70952. this._scene.lensFlareSystems.splice(index, 1);
  70953. };
  70954. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  70955. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  70956. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  70957. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  70958. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  70959. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  70960. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  70961. var parsedFlare = parsedLensFlareSystem.flares[index];
  70962. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  70963. }
  70964. return lensFlareSystem;
  70965. };
  70966. LensFlareSystem.prototype.serialize = function () {
  70967. var serializationObject = {};
  70968. serializationObject.id = this.id;
  70969. serializationObject.name = this.name;
  70970. serializationObject.emitterId = this.getEmitter().id;
  70971. serializationObject.borderLimit = this.borderLimit;
  70972. serializationObject.flares = [];
  70973. for (var index = 0; index < this.lensFlares.length; index++) {
  70974. var flare = this.lensFlares[index];
  70975. serializationObject.flares.push({
  70976. size: flare.size,
  70977. position: flare.position,
  70978. color: flare.color.asArray(),
  70979. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  70980. });
  70981. }
  70982. return serializationObject;
  70983. };
  70984. return LensFlareSystem;
  70985. }());
  70986. BABYLON.LensFlareSystem = LensFlareSystem;
  70987. })(BABYLON || (BABYLON = {}));
  70988. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  70989. var BABYLON;
  70990. (function (BABYLON) {
  70991. /**
  70992. * This is a holder class for the physics joint created by the physics plugin.
  70993. * It holds a set of functions to control the underlying joint.
  70994. */
  70995. var PhysicsJoint = /** @class */ (function () {
  70996. function PhysicsJoint(type, jointData) {
  70997. this.type = type;
  70998. this.jointData = jointData;
  70999. jointData.nativeParams = jointData.nativeParams || {};
  71000. }
  71001. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  71002. get: function () {
  71003. return this._physicsJoint;
  71004. },
  71005. set: function (newJoint) {
  71006. if (this._physicsJoint) {
  71007. //remove from the wolrd
  71008. }
  71009. this._physicsJoint = newJoint;
  71010. },
  71011. enumerable: true,
  71012. configurable: true
  71013. });
  71014. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  71015. set: function (physicsPlugin) {
  71016. this._physicsPlugin = physicsPlugin;
  71017. },
  71018. enumerable: true,
  71019. configurable: true
  71020. });
  71021. /**
  71022. * Execute a function that is physics-plugin specific.
  71023. * @param {Function} func the function that will be executed.
  71024. * It accepts two parameters: the physics world and the physics joint.
  71025. */
  71026. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  71027. func(this._physicsPlugin.world, this._physicsJoint);
  71028. };
  71029. //TODO check if the native joints are the same
  71030. //Joint Types
  71031. PhysicsJoint.DistanceJoint = 0;
  71032. PhysicsJoint.HingeJoint = 1;
  71033. PhysicsJoint.BallAndSocketJoint = 2;
  71034. PhysicsJoint.WheelJoint = 3;
  71035. PhysicsJoint.SliderJoint = 4;
  71036. //OIMO
  71037. PhysicsJoint.PrismaticJoint = 5;
  71038. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  71039. PhysicsJoint.UniversalJoint = 6;
  71040. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  71041. //Cannon
  71042. //Similar to a Ball-Joint. Different in params
  71043. PhysicsJoint.PointToPointJoint = 8;
  71044. //Cannon only at the moment
  71045. PhysicsJoint.SpringJoint = 9;
  71046. PhysicsJoint.LockJoint = 10;
  71047. return PhysicsJoint;
  71048. }());
  71049. BABYLON.PhysicsJoint = PhysicsJoint;
  71050. /**
  71051. * A class representing a physics distance joint.
  71052. */
  71053. var DistanceJoint = /** @class */ (function (_super) {
  71054. __extends(DistanceJoint, _super);
  71055. function DistanceJoint(jointData) {
  71056. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  71057. }
  71058. /**
  71059. * Update the predefined distance.
  71060. */
  71061. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  71062. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  71063. };
  71064. return DistanceJoint;
  71065. }(PhysicsJoint));
  71066. BABYLON.DistanceJoint = DistanceJoint;
  71067. var MotorEnabledJoint = /** @class */ (function (_super) {
  71068. __extends(MotorEnabledJoint, _super);
  71069. function MotorEnabledJoint(type, jointData) {
  71070. return _super.call(this, type, jointData) || this;
  71071. }
  71072. /**
  71073. * Set the motor values.
  71074. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71075. * @param {number} force the force to apply
  71076. * @param {number} maxForce max force for this motor.
  71077. */
  71078. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  71079. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71080. };
  71081. /**
  71082. * Set the motor's limits.
  71083. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71084. */
  71085. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71086. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71087. };
  71088. return MotorEnabledJoint;
  71089. }(PhysicsJoint));
  71090. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  71091. /**
  71092. * This class represents a single hinge physics joint
  71093. */
  71094. var HingeJoint = /** @class */ (function (_super) {
  71095. __extends(HingeJoint, _super);
  71096. function HingeJoint(jointData) {
  71097. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  71098. }
  71099. /**
  71100. * Set the motor values.
  71101. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71102. * @param {number} force the force to apply
  71103. * @param {number} maxForce max force for this motor.
  71104. */
  71105. HingeJoint.prototype.setMotor = function (force, maxForce) {
  71106. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71107. };
  71108. /**
  71109. * Set the motor's limits.
  71110. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71111. */
  71112. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71113. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71114. };
  71115. return HingeJoint;
  71116. }(MotorEnabledJoint));
  71117. BABYLON.HingeJoint = HingeJoint;
  71118. /**
  71119. * This class represents a dual hinge physics joint (same as wheel joint)
  71120. */
  71121. var Hinge2Joint = /** @class */ (function (_super) {
  71122. __extends(Hinge2Joint, _super);
  71123. function Hinge2Joint(jointData) {
  71124. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  71125. }
  71126. /**
  71127. * Set the motor values.
  71128. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71129. * @param {number} force the force to apply
  71130. * @param {number} maxForce max force for this motor.
  71131. * @param {motorIndex} the motor's index, 0 or 1.
  71132. */
  71133. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  71134. if (motorIndex === void 0) { motorIndex = 0; }
  71135. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  71136. };
  71137. /**
  71138. * Set the motor limits.
  71139. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71140. * @param {number} upperLimit the upper limit
  71141. * @param {number} lowerLimit lower limit
  71142. * @param {motorIndex} the motor's index, 0 or 1.
  71143. */
  71144. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  71145. if (motorIndex === void 0) { motorIndex = 0; }
  71146. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  71147. };
  71148. return Hinge2Joint;
  71149. }(MotorEnabledJoint));
  71150. BABYLON.Hinge2Joint = Hinge2Joint;
  71151. })(BABYLON || (BABYLON = {}));
  71152. //# sourceMappingURL=babylon.physicsJoint.js.map
  71153. var BABYLON;
  71154. (function (BABYLON) {
  71155. var PhysicsImpostor = /** @class */ (function () {
  71156. function PhysicsImpostor(object, type, _options, _scene) {
  71157. if (_options === void 0) { _options = { mass: 0 }; }
  71158. var _this = this;
  71159. this.object = object;
  71160. this.type = type;
  71161. this._options = _options;
  71162. this._scene = _scene;
  71163. this._bodyUpdateRequired = false;
  71164. this._onBeforePhysicsStepCallbacks = new Array();
  71165. this._onAfterPhysicsStepCallbacks = new Array();
  71166. this._onPhysicsCollideCallbacks = [];
  71167. this._deltaPosition = BABYLON.Vector3.Zero();
  71168. this._isDisposed = false;
  71169. //temp variables for parent rotation calculations
  71170. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  71171. this._tmpQuat = new BABYLON.Quaternion();
  71172. this._tmpQuat2 = new BABYLON.Quaternion();
  71173. /**
  71174. * this function is executed by the physics engine.
  71175. */
  71176. this.beforeStep = function () {
  71177. if (!_this._physicsEngine) {
  71178. return;
  71179. }
  71180. _this.object.translate(_this._deltaPosition, -1);
  71181. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  71182. _this.object.computeWorldMatrix(false);
  71183. if (_this.object.parent && _this.object.rotationQuaternion) {
  71184. _this.getParentsRotation();
  71185. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  71186. }
  71187. else {
  71188. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  71189. }
  71190. if (!_this._options.disableBidirectionalTransformation) {
  71191. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  71192. }
  71193. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  71194. func(_this);
  71195. });
  71196. };
  71197. /**
  71198. * this function is executed by the physics engine.
  71199. */
  71200. this.afterStep = function () {
  71201. if (!_this._physicsEngine) {
  71202. return;
  71203. }
  71204. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  71205. func(_this);
  71206. });
  71207. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  71208. // object has now its world rotation. needs to be converted to local.
  71209. if (_this.object.parent && _this.object.rotationQuaternion) {
  71210. _this.getParentsRotation();
  71211. _this._tmpQuat.conjugateInPlace();
  71212. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  71213. }
  71214. // take the position set and make it the absolute position of this object.
  71215. _this.object.setAbsolutePosition(_this.object.position);
  71216. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  71217. _this.object.translate(_this._deltaPosition, 1);
  71218. };
  71219. /**
  71220. * Legacy collision detection event support
  71221. */
  71222. this.onCollideEvent = null;
  71223. //event and body object due to cannon's event-based architecture.
  71224. this.onCollide = function (e) {
  71225. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  71226. return;
  71227. }
  71228. if (!_this._physicsEngine) {
  71229. return;
  71230. }
  71231. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  71232. if (otherImpostor) {
  71233. // Legacy collision detection event support
  71234. if (_this.onCollideEvent) {
  71235. _this.onCollideEvent(_this, otherImpostor);
  71236. }
  71237. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  71238. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  71239. }).forEach(function (obj) {
  71240. obj.callback(_this, otherImpostor);
  71241. });
  71242. }
  71243. };
  71244. //sanity check!
  71245. if (!this.object) {
  71246. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  71247. return;
  71248. }
  71249. //legacy support for old syntax.
  71250. if (!this._scene && object.getScene) {
  71251. this._scene = object.getScene();
  71252. }
  71253. if (!this._scene) {
  71254. return;
  71255. }
  71256. this._physicsEngine = this._scene.getPhysicsEngine();
  71257. if (!this._physicsEngine) {
  71258. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  71259. }
  71260. else {
  71261. //set the object's quaternion, if not set
  71262. if (!this.object.rotationQuaternion) {
  71263. if (this.object.rotation) {
  71264. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  71265. }
  71266. else {
  71267. this.object.rotationQuaternion = new BABYLON.Quaternion();
  71268. }
  71269. }
  71270. //default options params
  71271. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  71272. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  71273. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  71274. this._joints = [];
  71275. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  71276. if (!this.object.parent || this._options.ignoreParent) {
  71277. this._init();
  71278. }
  71279. else if (this.object.parent.physicsImpostor) {
  71280. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  71281. }
  71282. }
  71283. }
  71284. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  71285. get: function () {
  71286. return this._isDisposed;
  71287. },
  71288. enumerable: true,
  71289. configurable: true
  71290. });
  71291. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  71292. get: function () {
  71293. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  71294. },
  71295. set: function (value) {
  71296. this.setMass(value);
  71297. },
  71298. enumerable: true,
  71299. configurable: true
  71300. });
  71301. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  71302. get: function () {
  71303. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  71304. },
  71305. set: function (value) {
  71306. if (!this._physicsEngine) {
  71307. return;
  71308. }
  71309. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  71310. },
  71311. enumerable: true,
  71312. configurable: true
  71313. });
  71314. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  71315. get: function () {
  71316. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  71317. },
  71318. set: function (value) {
  71319. if (!this._physicsEngine) {
  71320. return;
  71321. }
  71322. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  71323. },
  71324. enumerable: true,
  71325. configurable: true
  71326. });
  71327. /**
  71328. * This function will completly initialize this impostor.
  71329. * It will create a new body - but only if this mesh has no parent.
  71330. * If it has, this impostor will not be used other than to define the impostor
  71331. * of the child mesh.
  71332. */
  71333. PhysicsImpostor.prototype._init = function () {
  71334. if (!this._physicsEngine) {
  71335. return;
  71336. }
  71337. this._physicsEngine.removeImpostor(this);
  71338. this.physicsBody = null;
  71339. this._parent = this._parent || this._getPhysicsParent();
  71340. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  71341. this._physicsEngine.addImpostor(this);
  71342. }
  71343. };
  71344. PhysicsImpostor.prototype._getPhysicsParent = function () {
  71345. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  71346. var parentMesh = this.object.parent;
  71347. return parentMesh.physicsImpostor;
  71348. }
  71349. return null;
  71350. };
  71351. /**
  71352. * Should a new body be generated.
  71353. */
  71354. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  71355. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  71356. };
  71357. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  71358. this.forceUpdate();
  71359. };
  71360. /**
  71361. * Force a regeneration of this or the parent's impostor's body.
  71362. * Use under cautious - This will remove all joints already implemented.
  71363. */
  71364. PhysicsImpostor.prototype.forceUpdate = function () {
  71365. this._init();
  71366. if (this.parent && !this._options.ignoreParent) {
  71367. this.parent.forceUpdate();
  71368. }
  71369. };
  71370. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  71371. /*public get mesh(): AbstractMesh {
  71372. return this._mesh;
  71373. }*/
  71374. /**
  71375. * Gets the body that holds this impostor. Either its own, or its parent.
  71376. */
  71377. get: function () {
  71378. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  71379. },
  71380. /**
  71381. * Set the physics body. Used mainly by the physics engine/plugin
  71382. */
  71383. set: function (physicsBody) {
  71384. if (this._physicsBody && this._physicsEngine) {
  71385. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  71386. }
  71387. this._physicsBody = physicsBody;
  71388. this.resetUpdateFlags();
  71389. },
  71390. enumerable: true,
  71391. configurable: true
  71392. });
  71393. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  71394. get: function () {
  71395. return !this._options.ignoreParent && this._parent ? this._parent : null;
  71396. },
  71397. set: function (value) {
  71398. this._parent = value;
  71399. },
  71400. enumerable: true,
  71401. configurable: true
  71402. });
  71403. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  71404. this._bodyUpdateRequired = false;
  71405. };
  71406. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  71407. if (this.object.getBoundingInfo) {
  71408. var q = this.object.rotationQuaternion;
  71409. //reset rotation
  71410. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  71411. //calculate the world matrix with no rotation
  71412. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71413. var boundingInfo = this.object.getBoundingInfo();
  71414. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  71415. //bring back the rotation
  71416. this.object.rotationQuaternion = q;
  71417. //calculate the world matrix with the new rotation
  71418. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71419. return size;
  71420. }
  71421. else {
  71422. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  71423. }
  71424. };
  71425. PhysicsImpostor.prototype.getObjectCenter = function () {
  71426. if (this.object.getBoundingInfo) {
  71427. var boundingInfo = this.object.getBoundingInfo();
  71428. return boundingInfo.boundingBox.centerWorld;
  71429. }
  71430. else {
  71431. return this.object.position;
  71432. }
  71433. };
  71434. /**
  71435. * Get a specific parametes from the options parameter.
  71436. */
  71437. PhysicsImpostor.prototype.getParam = function (paramName) {
  71438. return this._options[paramName];
  71439. };
  71440. /**
  71441. * Sets a specific parameter in the options given to the physics plugin
  71442. */
  71443. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  71444. this._options[paramName] = value;
  71445. this._bodyUpdateRequired = true;
  71446. };
  71447. /**
  71448. * Specifically change the body's mass option. Won't recreate the physics body object
  71449. */
  71450. PhysicsImpostor.prototype.setMass = function (mass) {
  71451. if (this.getParam("mass") !== mass) {
  71452. this.setParam("mass", mass);
  71453. }
  71454. if (this._physicsEngine) {
  71455. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  71456. }
  71457. };
  71458. PhysicsImpostor.prototype.getLinearVelocity = function () {
  71459. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  71460. };
  71461. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  71462. if (this._physicsEngine) {
  71463. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  71464. }
  71465. };
  71466. PhysicsImpostor.prototype.getAngularVelocity = function () {
  71467. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  71468. };
  71469. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  71470. if (this._physicsEngine) {
  71471. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  71472. }
  71473. };
  71474. /**
  71475. * Execute a function with the physics plugin native code.
  71476. * Provide a function the will have two variables - the world object and the physics body object.
  71477. */
  71478. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  71479. if (this._physicsEngine) {
  71480. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  71481. }
  71482. };
  71483. /**
  71484. * Register a function that will be executed before the physics world is stepping forward.
  71485. */
  71486. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  71487. this._onBeforePhysicsStepCallbacks.push(func);
  71488. };
  71489. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  71490. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  71491. if (index > -1) {
  71492. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  71493. }
  71494. else {
  71495. BABYLON.Tools.Warn("Function to remove was not found");
  71496. }
  71497. };
  71498. /**
  71499. * Register a function that will be executed after the physics step
  71500. */
  71501. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  71502. this._onAfterPhysicsStepCallbacks.push(func);
  71503. };
  71504. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  71505. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  71506. if (index > -1) {
  71507. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  71508. }
  71509. else {
  71510. BABYLON.Tools.Warn("Function to remove was not found");
  71511. }
  71512. };
  71513. /**
  71514. * register a function that will be executed when this impostor collides against a different body.
  71515. */
  71516. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  71517. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71518. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  71519. };
  71520. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  71521. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71522. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  71523. if (index > -1) {
  71524. this._onPhysicsCollideCallbacks.splice(index, 1);
  71525. }
  71526. else {
  71527. BABYLON.Tools.Warn("Function to remove was not found");
  71528. }
  71529. };
  71530. PhysicsImpostor.prototype.getParentsRotation = function () {
  71531. var parent = this.object.parent;
  71532. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  71533. while (parent) {
  71534. if (parent.rotationQuaternion) {
  71535. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  71536. }
  71537. else {
  71538. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  71539. }
  71540. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  71541. parent = parent.parent;
  71542. }
  71543. return this._tmpQuat;
  71544. };
  71545. /**
  71546. * Apply a force
  71547. */
  71548. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  71549. if (this._physicsEngine) {
  71550. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  71551. }
  71552. return this;
  71553. };
  71554. /**
  71555. * Apply an impulse
  71556. */
  71557. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  71558. if (this._physicsEngine) {
  71559. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  71560. }
  71561. return this;
  71562. };
  71563. /**
  71564. * A help function to create a joint.
  71565. */
  71566. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  71567. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  71568. this.addJoint(otherImpostor, joint);
  71569. return this;
  71570. };
  71571. /**
  71572. * Add a joint to this impostor with a different impostor.
  71573. */
  71574. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  71575. this._joints.push({
  71576. otherImpostor: otherImpostor,
  71577. joint: joint
  71578. });
  71579. if (this._physicsEngine) {
  71580. this._physicsEngine.addJoint(this, otherImpostor, joint);
  71581. }
  71582. return this;
  71583. };
  71584. /**
  71585. * Will keep this body still, in a sleep mode.
  71586. */
  71587. PhysicsImpostor.prototype.sleep = function () {
  71588. if (this._physicsEngine) {
  71589. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  71590. }
  71591. return this;
  71592. };
  71593. /**
  71594. * Wake the body up.
  71595. */
  71596. PhysicsImpostor.prototype.wakeUp = function () {
  71597. if (this._physicsEngine) {
  71598. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  71599. }
  71600. return this;
  71601. };
  71602. PhysicsImpostor.prototype.clone = function (newObject) {
  71603. if (!newObject)
  71604. return null;
  71605. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  71606. };
  71607. PhysicsImpostor.prototype.dispose = function () {
  71608. var _this = this;
  71609. //no dispose if no physics engine is available.
  71610. if (!this._physicsEngine) {
  71611. return;
  71612. }
  71613. this._joints.forEach(function (j) {
  71614. if (_this._physicsEngine) {
  71615. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  71616. }
  71617. });
  71618. //dispose the physics body
  71619. this._physicsEngine.removeImpostor(this);
  71620. if (this.parent) {
  71621. this.parent.forceUpdate();
  71622. }
  71623. else {
  71624. /*this._object.getChildMeshes().forEach(function(mesh) {
  71625. if (mesh.physicsImpostor) {
  71626. if (disposeChildren) {
  71627. mesh.physicsImpostor.dispose();
  71628. mesh.physicsImpostor = null;
  71629. }
  71630. }
  71631. })*/
  71632. }
  71633. this._isDisposed = true;
  71634. };
  71635. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  71636. this._deltaPosition.copyFrom(position);
  71637. };
  71638. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  71639. if (!this._deltaRotation) {
  71640. this._deltaRotation = new BABYLON.Quaternion();
  71641. }
  71642. this._deltaRotation.copyFrom(rotation);
  71643. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  71644. };
  71645. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  71646. if (this._physicsEngine) {
  71647. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  71648. }
  71649. return this;
  71650. };
  71651. PhysicsImpostor.prototype.getRadius = function () {
  71652. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  71653. };
  71654. /**
  71655. * Sync a bone with this impostor
  71656. * @param bone The bone to sync to the impostor.
  71657. * @param boneMesh The mesh that the bone is influencing.
  71658. * @param jointPivot The pivot of the joint / bone in local space.
  71659. * @param distToJoint Optional distance from the impostor to the joint.
  71660. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71661. */
  71662. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  71663. var tempVec = PhysicsImpostor._tmpVecs[0];
  71664. var mesh = this.object;
  71665. if (mesh.rotationQuaternion) {
  71666. if (adjustRotation) {
  71667. var tempQuat = PhysicsImpostor._tmpQuat;
  71668. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  71669. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  71670. }
  71671. else {
  71672. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  71673. }
  71674. }
  71675. tempVec.x = 0;
  71676. tempVec.y = 0;
  71677. tempVec.z = 0;
  71678. if (jointPivot) {
  71679. tempVec.x = jointPivot.x;
  71680. tempVec.y = jointPivot.y;
  71681. tempVec.z = jointPivot.z;
  71682. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  71683. if (distToJoint === undefined || distToJoint === null) {
  71684. distToJoint = jointPivot.length();
  71685. }
  71686. tempVec.x *= distToJoint;
  71687. tempVec.y *= distToJoint;
  71688. tempVec.z *= distToJoint;
  71689. }
  71690. if (bone.getParent()) {
  71691. tempVec.addInPlace(mesh.getAbsolutePosition());
  71692. bone.setAbsolutePosition(tempVec, boneMesh);
  71693. }
  71694. else {
  71695. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  71696. boneMesh.position.x -= tempVec.x;
  71697. boneMesh.position.y -= tempVec.y;
  71698. boneMesh.position.z -= tempVec.z;
  71699. }
  71700. };
  71701. /**
  71702. * Sync impostor to a bone
  71703. * @param bone The bone that the impostor will be synced to.
  71704. * @param boneMesh The mesh that the bone is influencing.
  71705. * @param jointPivot The pivot of the joint / bone in local space.
  71706. * @param distToJoint Optional distance from the impostor to the joint.
  71707. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71708. * @param boneAxis Optional vector3 axis the bone is aligned with
  71709. */
  71710. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  71711. var mesh = this.object;
  71712. if (mesh.rotationQuaternion) {
  71713. if (adjustRotation) {
  71714. var tempQuat = PhysicsImpostor._tmpQuat;
  71715. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  71716. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  71717. }
  71718. else {
  71719. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  71720. }
  71721. }
  71722. var pos = PhysicsImpostor._tmpVecs[0];
  71723. var boneDir = PhysicsImpostor._tmpVecs[1];
  71724. if (!boneAxis) {
  71725. boneAxis = PhysicsImpostor._tmpVecs[2];
  71726. boneAxis.x = 0;
  71727. boneAxis.y = 1;
  71728. boneAxis.z = 0;
  71729. }
  71730. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  71731. bone.getAbsolutePositionToRef(boneMesh, pos);
  71732. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  71733. distToJoint = jointPivot.length();
  71734. }
  71735. if (distToJoint !== undefined && distToJoint !== null) {
  71736. pos.x += boneDir.x * distToJoint;
  71737. pos.y += boneDir.y * distToJoint;
  71738. pos.z += boneDir.z * distToJoint;
  71739. }
  71740. mesh.setAbsolutePosition(pos);
  71741. };
  71742. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  71743. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  71744. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71745. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  71746. //Impostor types
  71747. PhysicsImpostor.NoImpostor = 0;
  71748. PhysicsImpostor.SphereImpostor = 1;
  71749. PhysicsImpostor.BoxImpostor = 2;
  71750. PhysicsImpostor.PlaneImpostor = 3;
  71751. PhysicsImpostor.MeshImpostor = 4;
  71752. PhysicsImpostor.CylinderImpostor = 7;
  71753. PhysicsImpostor.ParticleImpostor = 8;
  71754. PhysicsImpostor.HeightmapImpostor = 9;
  71755. return PhysicsImpostor;
  71756. }());
  71757. BABYLON.PhysicsImpostor = PhysicsImpostor;
  71758. })(BABYLON || (BABYLON = {}));
  71759. //# sourceMappingURL=babylon.physicsImpostor.js.map
  71760. var BABYLON;
  71761. (function (BABYLON) {
  71762. var PhysicsEngine = /** @class */ (function () {
  71763. function PhysicsEngine(gravity, _physicsPlugin) {
  71764. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  71765. this._physicsPlugin = _physicsPlugin;
  71766. //new methods and parameters
  71767. this._impostors = [];
  71768. this._joints = [];
  71769. if (!this._physicsPlugin.isSupported()) {
  71770. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  71771. + "Please make sure it is included.");
  71772. }
  71773. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  71774. this.setGravity(gravity);
  71775. this.setTimeStep();
  71776. }
  71777. PhysicsEngine.prototype.setGravity = function (gravity) {
  71778. this.gravity = gravity;
  71779. this._physicsPlugin.setGravity(this.gravity);
  71780. };
  71781. /**
  71782. * Set the time step of the physics engine.
  71783. * default is 1/60.
  71784. * To slow it down, enter 1/600 for example.
  71785. * To speed it up, 1/30
  71786. * @param {number} newTimeStep the new timestep to apply to this world.
  71787. */
  71788. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  71789. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  71790. this._physicsPlugin.setTimeStep(newTimeStep);
  71791. };
  71792. /**
  71793. * Get the time step of the physics engine.
  71794. */
  71795. PhysicsEngine.prototype.getTimeStep = function () {
  71796. return this._physicsPlugin.getTimeStep();
  71797. };
  71798. PhysicsEngine.prototype.dispose = function () {
  71799. this._impostors.forEach(function (impostor) {
  71800. impostor.dispose();
  71801. });
  71802. this._physicsPlugin.dispose();
  71803. };
  71804. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  71805. return this._physicsPlugin.name;
  71806. };
  71807. /**
  71808. * Adding a new impostor for the impostor tracking.
  71809. * This will be done by the impostor itself.
  71810. * @param {PhysicsImpostor} impostor the impostor to add
  71811. */
  71812. PhysicsEngine.prototype.addImpostor = function (impostor) {
  71813. impostor.uniqueId = this._impostors.push(impostor);
  71814. //if no parent, generate the body
  71815. if (!impostor.parent) {
  71816. this._physicsPlugin.generatePhysicsBody(impostor);
  71817. }
  71818. };
  71819. /**
  71820. * Remove an impostor from the engine.
  71821. * This impostor and its mesh will not longer be updated by the physics engine.
  71822. * @param {PhysicsImpostor} impostor the impostor to remove
  71823. */
  71824. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  71825. var index = this._impostors.indexOf(impostor);
  71826. if (index > -1) {
  71827. var removed = this._impostors.splice(index, 1);
  71828. //Is it needed?
  71829. if (removed.length) {
  71830. //this will also remove it from the world.
  71831. removed[0].physicsBody = null;
  71832. }
  71833. }
  71834. };
  71835. /**
  71836. * Add a joint to the physics engine
  71837. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  71838. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  71839. * @param {PhysicsJoint} the joint that will connect both impostors.
  71840. */
  71841. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  71842. var impostorJoint = {
  71843. mainImpostor: mainImpostor,
  71844. connectedImpostor: connectedImpostor,
  71845. joint: joint
  71846. };
  71847. joint.physicsPlugin = this._physicsPlugin;
  71848. this._joints.push(impostorJoint);
  71849. this._physicsPlugin.generateJoint(impostorJoint);
  71850. };
  71851. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  71852. var matchingJoints = this._joints.filter(function (impostorJoint) {
  71853. return (impostorJoint.connectedImpostor === connectedImpostor
  71854. && impostorJoint.joint === joint
  71855. && impostorJoint.mainImpostor === mainImpostor);
  71856. });
  71857. if (matchingJoints.length) {
  71858. this._physicsPlugin.removeJoint(matchingJoints[0]);
  71859. //TODO remove it from the list as well
  71860. }
  71861. };
  71862. /**
  71863. * Called by the scene. no need to call it.
  71864. */
  71865. PhysicsEngine.prototype._step = function (delta) {
  71866. var _this = this;
  71867. //check if any mesh has no body / requires an update
  71868. this._impostors.forEach(function (impostor) {
  71869. if (impostor.isBodyInitRequired()) {
  71870. _this._physicsPlugin.generatePhysicsBody(impostor);
  71871. }
  71872. });
  71873. if (delta > 0.1) {
  71874. delta = 0.1;
  71875. }
  71876. else if (delta <= 0) {
  71877. delta = 1.0 / 60.0;
  71878. }
  71879. this._physicsPlugin.executeStep(delta, this._impostors);
  71880. };
  71881. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  71882. return this._physicsPlugin;
  71883. };
  71884. PhysicsEngine.prototype.getImpostors = function () {
  71885. return this._impostors;
  71886. };
  71887. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  71888. for (var i = 0; i < this._impostors.length; ++i) {
  71889. if (this._impostors[i].object === object) {
  71890. return this._impostors[i];
  71891. }
  71892. }
  71893. return null;
  71894. };
  71895. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  71896. for (var i = 0; i < this._impostors.length; ++i) {
  71897. if (this._impostors[i].physicsBody === body) {
  71898. return this._impostors[i];
  71899. }
  71900. }
  71901. return null;
  71902. };
  71903. // Statics
  71904. PhysicsEngine.Epsilon = 0.001;
  71905. return PhysicsEngine;
  71906. }());
  71907. BABYLON.PhysicsEngine = PhysicsEngine;
  71908. })(BABYLON || (BABYLON = {}));
  71909. //# sourceMappingURL=babylon.physicsEngine.js.map
  71910. var BABYLON;
  71911. (function (BABYLON) {
  71912. var PhysicsHelper = /** @class */ (function () {
  71913. function PhysicsHelper(scene) {
  71914. this._scene = scene;
  71915. this._physicsEngine = this._scene.getPhysicsEngine();
  71916. if (!this._physicsEngine) {
  71917. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  71918. }
  71919. }
  71920. /**
  71921. * @param {Vector3} origin the origin of the explosion
  71922. * @param {number} radius the explosion radius
  71923. * @param {number} strength the explosion strength
  71924. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71925. */
  71926. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  71927. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71928. if (!this._physicsEngine) {
  71929. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  71930. return null;
  71931. }
  71932. var impostors = this._physicsEngine.getImpostors();
  71933. if (impostors.length === 0) {
  71934. return null;
  71935. }
  71936. var event = new PhysicsRadialExplosionEvent(this._scene);
  71937. impostors.forEach(function (impostor) {
  71938. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71939. if (!impostorForceAndContactPoint) {
  71940. return;
  71941. }
  71942. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71943. });
  71944. event.dispose(false);
  71945. return event;
  71946. };
  71947. /**
  71948. * @param {Vector3} origin the origin of the explosion
  71949. * @param {number} radius the explosion radius
  71950. * @param {number} strength the explosion strength
  71951. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71952. */
  71953. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  71954. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71955. if (!this._physicsEngine) {
  71956. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71957. return null;
  71958. }
  71959. var impostors = this._physicsEngine.getImpostors();
  71960. if (impostors.length === 0) {
  71961. return null;
  71962. }
  71963. var event = new PhysicsRadialExplosionEvent(this._scene);
  71964. impostors.forEach(function (impostor) {
  71965. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71966. if (!impostorForceAndContactPoint) {
  71967. return;
  71968. }
  71969. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71970. });
  71971. event.dispose(false);
  71972. return event;
  71973. };
  71974. /**
  71975. * @param {Vector3} origin the origin of the explosion
  71976. * @param {number} radius the explosion radius
  71977. * @param {number} strength the explosion strength
  71978. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71979. */
  71980. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  71981. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71982. if (!this._physicsEngine) {
  71983. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71984. return null;
  71985. }
  71986. var impostors = this._physicsEngine.getImpostors();
  71987. if (impostors.length === 0) {
  71988. return null;
  71989. }
  71990. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  71991. event.dispose(false);
  71992. return event;
  71993. };
  71994. /**
  71995. * @param {Vector3} origin the origin of the updraft
  71996. * @param {number} radius the radius of the updraft
  71997. * @param {number} strength the strength of the updraft
  71998. * @param {number} height the height of the updraft
  71999. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  72000. */
  72001. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  72002. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  72003. if (!this._physicsEngine) {
  72004. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72005. return null;
  72006. }
  72007. if (this._physicsEngine.getImpostors().length === 0) {
  72008. return null;
  72009. }
  72010. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  72011. event.dispose(false);
  72012. return event;
  72013. };
  72014. /**
  72015. * @param {Vector3} origin the of the vortex
  72016. * @param {number} radius the radius of the vortex
  72017. * @param {number} strength the strength of the vortex
  72018. * @param {number} height the height of the vortex
  72019. */
  72020. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  72021. if (!this._physicsEngine) {
  72022. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72023. return null;
  72024. }
  72025. if (this._physicsEngine.getImpostors().length === 0) {
  72026. return null;
  72027. }
  72028. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  72029. event.dispose(false);
  72030. return event;
  72031. };
  72032. return PhysicsHelper;
  72033. }());
  72034. BABYLON.PhysicsHelper = PhysicsHelper;
  72035. /***** Radial explosion *****/
  72036. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  72037. function PhysicsRadialExplosionEvent(scene) {
  72038. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  72039. this._rays = [];
  72040. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  72041. this._scene = scene;
  72042. }
  72043. /**
  72044. * Returns the data related to the radial explosion event (sphere & rays).
  72045. * @returns {PhysicsRadialExplosionEventData}
  72046. */
  72047. PhysicsRadialExplosionEvent.prototype.getData = function () {
  72048. this._dataFetched = true;
  72049. return {
  72050. sphere: this._sphere,
  72051. rays: this._rays,
  72052. };
  72053. };
  72054. /**
  72055. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  72056. * @param impostor
  72057. * @param {Vector3} origin the origin of the explosion
  72058. * @param {number} radius the explosion radius
  72059. * @param {number} strength the explosion strength
  72060. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  72061. * @returns {Nullable<PhysicsForceAndContactPoint>}
  72062. */
  72063. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  72064. if (impostor.mass === 0) {
  72065. return null;
  72066. }
  72067. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  72068. return null;
  72069. }
  72070. if (impostor.object.getClassName() !== 'Mesh') {
  72071. return null;
  72072. }
  72073. var impostorObject = impostor.object;
  72074. var impostorObjectCenter = impostor.getObjectCenter();
  72075. var direction = impostorObjectCenter.subtract(origin);
  72076. var ray = new BABYLON.Ray(origin, direction, radius);
  72077. this._rays.push(ray);
  72078. var hit = ray.intersectsMesh(impostorObject);
  72079. var contactPoint = hit.pickedPoint;
  72080. if (!contactPoint) {
  72081. return null;
  72082. }
  72083. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  72084. if (distanceFromOrigin > radius) {
  72085. return null;
  72086. }
  72087. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  72088. ? strength
  72089. : strength * (1 - (distanceFromOrigin / radius));
  72090. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72091. return { force: force, contactPoint: contactPoint };
  72092. };
  72093. /**
  72094. * Disposes the sphere.
  72095. * @param {bolean} force
  72096. */
  72097. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  72098. var _this = this;
  72099. if (force === void 0) { force = true; }
  72100. if (force) {
  72101. this._sphere.dispose();
  72102. }
  72103. else {
  72104. setTimeout(function () {
  72105. if (!_this._dataFetched) {
  72106. _this._sphere.dispose();
  72107. }
  72108. }, 0);
  72109. }
  72110. };
  72111. /*** Helpers ***/
  72112. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  72113. if (!this._sphere) {
  72114. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  72115. this._sphere.isVisible = false;
  72116. }
  72117. };
  72118. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  72119. var impostorObject = impostor.object;
  72120. this._prepareSphere();
  72121. this._sphere.position = origin;
  72122. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  72123. this._sphere._updateBoundingInfo();
  72124. this._sphere.computeWorldMatrix(true);
  72125. return this._sphere.intersectsMesh(impostorObject, true);
  72126. };
  72127. return PhysicsRadialExplosionEvent;
  72128. }());
  72129. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  72130. /***** Gravitational Field *****/
  72131. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  72132. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  72133. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72134. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72135. this._physicsHelper = physicsHelper;
  72136. this._scene = scene;
  72137. this._origin = origin;
  72138. this._radius = radius;
  72139. this._strength = strength;
  72140. this._falloff = falloff;
  72141. this._tickCallback = this._tick.bind(this);
  72142. }
  72143. /**
  72144. * Returns the data related to the gravitational field event (sphere).
  72145. * @returns {PhysicsGravitationalFieldEventData}
  72146. */
  72147. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  72148. this._dataFetched = true;
  72149. return {
  72150. sphere: this._sphere,
  72151. };
  72152. };
  72153. /**
  72154. * Enables the gravitational field.
  72155. */
  72156. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  72157. this._tickCallback.call(this);
  72158. this._scene.registerBeforeRender(this._tickCallback);
  72159. };
  72160. /**
  72161. * Disables the gravitational field.
  72162. */
  72163. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  72164. this._scene.unregisterBeforeRender(this._tickCallback);
  72165. };
  72166. /**
  72167. * Disposes the sphere.
  72168. * @param {bolean} force
  72169. */
  72170. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  72171. var _this = this;
  72172. if (force === void 0) { force = true; }
  72173. if (force) {
  72174. this._sphere.dispose();
  72175. }
  72176. else {
  72177. setTimeout(function () {
  72178. if (!_this._dataFetched) {
  72179. _this._sphere.dispose();
  72180. }
  72181. }, 0);
  72182. }
  72183. };
  72184. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  72185. // Since the params won't change, we fetch the event only once
  72186. if (this._sphere) {
  72187. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72188. }
  72189. else {
  72190. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72191. if (radialExplosionEvent) {
  72192. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  72193. }
  72194. }
  72195. };
  72196. return PhysicsGravitationalFieldEvent;
  72197. }());
  72198. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  72199. /***** Updraft *****/
  72200. var PhysicsUpdraftEvent = /** @class */ (function () {
  72201. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  72202. this._scene = _scene;
  72203. this._origin = _origin;
  72204. this._radius = _radius;
  72205. this._strength = _strength;
  72206. this._height = _height;
  72207. this._updraftMode = _updraftMode;
  72208. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72209. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  72210. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72211. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72212. this._physicsEngine = this._scene.getPhysicsEngine();
  72213. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72214. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72215. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72216. this._originDirection = this._origin.subtract(this._originTop).normalize();
  72217. }
  72218. this._tickCallback = this._tick.bind(this);
  72219. }
  72220. /**
  72221. * Returns the data related to the updraft event (cylinder).
  72222. * @returns {PhysicsUpdraftEventData}
  72223. */
  72224. PhysicsUpdraftEvent.prototype.getData = function () {
  72225. this._dataFetched = true;
  72226. return {
  72227. cylinder: this._cylinder,
  72228. };
  72229. };
  72230. /**
  72231. * Enables the updraft.
  72232. */
  72233. PhysicsUpdraftEvent.prototype.enable = function () {
  72234. this._tickCallback.call(this);
  72235. this._scene.registerBeforeRender(this._tickCallback);
  72236. };
  72237. /**
  72238. * Disables the cortex.
  72239. */
  72240. PhysicsUpdraftEvent.prototype.disable = function () {
  72241. this._scene.unregisterBeforeRender(this._tickCallback);
  72242. };
  72243. /**
  72244. * Disposes the sphere.
  72245. * @param {bolean} force
  72246. */
  72247. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  72248. var _this = this;
  72249. if (force === void 0) { force = true; }
  72250. if (force) {
  72251. this._cylinder.dispose();
  72252. }
  72253. else {
  72254. setTimeout(function () {
  72255. if (!_this._dataFetched) {
  72256. _this._cylinder.dispose();
  72257. }
  72258. }, 0);
  72259. }
  72260. };
  72261. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72262. if (impostor.mass === 0) {
  72263. return null;
  72264. }
  72265. if (!this._intersectsWithCylinder(impostor)) {
  72266. return null;
  72267. }
  72268. var impostorObjectCenter = impostor.getObjectCenter();
  72269. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72270. var direction = this._originDirection;
  72271. }
  72272. else {
  72273. var direction = impostorObjectCenter.subtract(this._originTop);
  72274. }
  72275. var multiplier = this._strength * -1;
  72276. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72277. return { force: force, contactPoint: impostorObjectCenter };
  72278. };
  72279. PhysicsUpdraftEvent.prototype._tick = function () {
  72280. var _this = this;
  72281. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72282. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72283. if (!impostorForceAndContactPoint) {
  72284. return;
  72285. }
  72286. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72287. });
  72288. };
  72289. /*** Helpers ***/
  72290. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  72291. if (!this._cylinder) {
  72292. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  72293. height: this._height,
  72294. diameter: this._radius * 2,
  72295. }, this._scene);
  72296. this._cylinder.isVisible = false;
  72297. }
  72298. };
  72299. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  72300. var impostorObject = impostor.object;
  72301. this._prepareCylinder();
  72302. this._cylinder.position = this._cylinderPosition;
  72303. return this._cylinder.intersectsMesh(impostorObject, true);
  72304. };
  72305. return PhysicsUpdraftEvent;
  72306. }());
  72307. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  72308. /***** Vortex *****/
  72309. var PhysicsVortexEvent = /** @class */ (function () {
  72310. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  72311. this._scene = _scene;
  72312. this._origin = _origin;
  72313. this._radius = _radius;
  72314. this._strength = _strength;
  72315. this._height = _height;
  72316. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72317. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  72318. this._updraftMultiplier = 0.02;
  72319. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72320. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72321. this._physicsEngine = this._scene.getPhysicsEngine();
  72322. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72323. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72324. this._tickCallback = this._tick.bind(this);
  72325. }
  72326. /**
  72327. * Returns the data related to the vortex event (cylinder).
  72328. * @returns {PhysicsVortexEventData}
  72329. */
  72330. PhysicsVortexEvent.prototype.getData = function () {
  72331. this._dataFetched = true;
  72332. return {
  72333. cylinder: this._cylinder,
  72334. };
  72335. };
  72336. /**
  72337. * Enables the vortex.
  72338. */
  72339. PhysicsVortexEvent.prototype.enable = function () {
  72340. this._tickCallback.call(this);
  72341. this._scene.registerBeforeRender(this._tickCallback);
  72342. };
  72343. /**
  72344. * Disables the cortex.
  72345. */
  72346. PhysicsVortexEvent.prototype.disable = function () {
  72347. this._scene.unregisterBeforeRender(this._tickCallback);
  72348. };
  72349. /**
  72350. * Disposes the sphere.
  72351. * @param {bolean} force
  72352. */
  72353. PhysicsVortexEvent.prototype.dispose = function (force) {
  72354. var _this = this;
  72355. if (force === void 0) { force = true; }
  72356. if (force) {
  72357. this._cylinder.dispose();
  72358. }
  72359. else {
  72360. setTimeout(function () {
  72361. if (!_this._dataFetched) {
  72362. _this._cylinder.dispose();
  72363. }
  72364. }, 0);
  72365. }
  72366. };
  72367. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72368. if (impostor.mass === 0) {
  72369. return null;
  72370. }
  72371. if (!this._intersectsWithCylinder(impostor)) {
  72372. return null;
  72373. }
  72374. if (impostor.object.getClassName() !== 'Mesh') {
  72375. return null;
  72376. }
  72377. var impostorObject = impostor.object;
  72378. var impostorObjectCenter = impostor.getObjectCenter();
  72379. 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)
  72380. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  72381. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  72382. var hit = ray.intersectsMesh(impostorObject);
  72383. var contactPoint = hit.pickedPoint;
  72384. if (!contactPoint) {
  72385. return null;
  72386. }
  72387. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  72388. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  72389. var directionToOrigin = contactPoint.normalize();
  72390. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72391. directionToOrigin = directionToOrigin.negate();
  72392. }
  72393. // TODO: find a more physically based solution
  72394. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72395. var forceX = directionToOrigin.x * this._strength / 8;
  72396. var forceY = directionToOrigin.y * this._updraftMultiplier;
  72397. var forceZ = directionToOrigin.z * this._strength / 8;
  72398. }
  72399. else {
  72400. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  72401. var forceY = this._originTop.y * this._updraftMultiplier;
  72402. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  72403. }
  72404. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  72405. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  72406. return { force: force, contactPoint: impostorObjectCenter };
  72407. };
  72408. PhysicsVortexEvent.prototype._tick = function () {
  72409. var _this = this;
  72410. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72411. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72412. if (!impostorForceAndContactPoint) {
  72413. return;
  72414. }
  72415. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72416. });
  72417. };
  72418. /*** Helpers ***/
  72419. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  72420. if (!this._cylinder) {
  72421. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  72422. height: this._height,
  72423. diameter: this._radius * 2,
  72424. }, this._scene);
  72425. this._cylinder.isVisible = false;
  72426. }
  72427. };
  72428. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  72429. var impostorObject = impostor.object;
  72430. this._prepareCylinder();
  72431. this._cylinder.position = this._cylinderPosition;
  72432. return this._cylinder.intersectsMesh(impostorObject, true);
  72433. };
  72434. return PhysicsVortexEvent;
  72435. }());
  72436. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  72437. /***** Enums *****/
  72438. /**
  72439. * The strenght of the force in correspondence to the distance of the affected object
  72440. */
  72441. var PhysicsRadialImpulseFalloff;
  72442. (function (PhysicsRadialImpulseFalloff) {
  72443. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  72444. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  72445. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  72446. /**
  72447. * The strenght of the force in correspondence to the distance of the affected object
  72448. */
  72449. var PhysicsUpdraftMode;
  72450. (function (PhysicsUpdraftMode) {
  72451. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  72452. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  72453. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  72454. })(BABYLON || (BABYLON = {}));
  72455. //# sourceMappingURL=babylon.physicsHelper.js.map
  72456. var BABYLON;
  72457. (function (BABYLON) {
  72458. var CannonJSPlugin = /** @class */ (function () {
  72459. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  72460. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  72461. if (iterations === void 0) { iterations = 10; }
  72462. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  72463. this.name = "CannonJSPlugin";
  72464. this._physicsMaterials = new Array();
  72465. this._fixedTimeStep = 1 / 60;
  72466. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  72467. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  72468. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  72469. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  72470. this._tmpPosition = BABYLON.Vector3.Zero();
  72471. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  72472. this._tmpUnityRotation = new BABYLON.Quaternion();
  72473. if (!this.isSupported()) {
  72474. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  72475. return;
  72476. }
  72477. this._extendNamespace();
  72478. this.world = new this.BJSCANNON.World();
  72479. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  72480. this.world.solver.iterations = iterations;
  72481. }
  72482. CannonJSPlugin.prototype.setGravity = function (gravity) {
  72483. this.world.gravity.copy(gravity);
  72484. };
  72485. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  72486. this._fixedTimeStep = timeStep;
  72487. };
  72488. CannonJSPlugin.prototype.getTimeStep = function () {
  72489. return this._fixedTimeStep;
  72490. };
  72491. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  72492. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  72493. };
  72494. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72495. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72496. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72497. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  72498. };
  72499. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72500. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72501. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72502. impostor.physicsBody.applyForce(impulse, worldPoint);
  72503. };
  72504. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72505. //parent-child relationship. Does this impostor has a parent impostor?
  72506. if (impostor.parent) {
  72507. if (impostor.physicsBody) {
  72508. this.removePhysicsBody(impostor);
  72509. //TODO is that needed?
  72510. impostor.forceUpdate();
  72511. }
  72512. return;
  72513. }
  72514. //should a new body be created for this impostor?
  72515. if (impostor.isBodyInitRequired()) {
  72516. var shape = this._createShape(impostor);
  72517. //unregister events, if body is being changed
  72518. var oldBody = impostor.physicsBody;
  72519. if (oldBody) {
  72520. this.removePhysicsBody(impostor);
  72521. }
  72522. //create the body and material
  72523. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  72524. var bodyCreationObject = {
  72525. mass: impostor.getParam("mass"),
  72526. material: material
  72527. };
  72528. // A simple extend, in case native options were used.
  72529. var nativeOptions = impostor.getParam("nativeOptions");
  72530. for (var key in nativeOptions) {
  72531. if (nativeOptions.hasOwnProperty(key)) {
  72532. bodyCreationObject[key] = nativeOptions[key];
  72533. }
  72534. }
  72535. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  72536. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  72537. this.world.addEventListener("preStep", impostor.beforeStep);
  72538. this.world.addEventListener("postStep", impostor.afterStep);
  72539. impostor.physicsBody.addShape(shape);
  72540. this.world.add(impostor.physicsBody);
  72541. //try to keep the body moving in the right direction by taking old properties.
  72542. //Should be tested!
  72543. if (oldBody) {
  72544. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  72545. impostor.physicsBody[param].copy(oldBody[param]);
  72546. });
  72547. }
  72548. this._processChildMeshes(impostor);
  72549. }
  72550. //now update the body's transformation
  72551. this._updatePhysicsBodyTransformation(impostor);
  72552. };
  72553. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  72554. var _this = this;
  72555. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  72556. var currentRotation = mainImpostor.object.rotationQuaternion;
  72557. if (meshChildren.length) {
  72558. var processMesh = function (localPosition, mesh) {
  72559. if (!currentRotation || !mesh.rotationQuaternion) {
  72560. return;
  72561. }
  72562. var childImpostor = mesh.getPhysicsImpostor();
  72563. if (childImpostor) {
  72564. var parent = childImpostor.parent;
  72565. if (parent !== mainImpostor) {
  72566. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  72567. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  72568. if (childImpostor.physicsBody) {
  72569. _this.removePhysicsBody(childImpostor);
  72570. childImpostor.physicsBody = null;
  72571. }
  72572. childImpostor.parent = mainImpostor;
  72573. childImpostor.resetUpdateFlags();
  72574. 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));
  72575. //Add the mass of the children.
  72576. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  72577. }
  72578. }
  72579. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  72580. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  72581. };
  72582. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  72583. }
  72584. };
  72585. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72586. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  72587. this.world.removeEventListener("preStep", impostor.beforeStep);
  72588. this.world.removeEventListener("postStep", impostor.afterStep);
  72589. this.world.remove(impostor.physicsBody);
  72590. };
  72591. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72592. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72593. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72594. if (!mainBody || !connectedBody) {
  72595. return;
  72596. }
  72597. var constraint;
  72598. var jointData = impostorJoint.joint.jointData;
  72599. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  72600. var constraintData = {
  72601. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  72602. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  72603. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  72604. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  72605. maxForce: jointData.nativeParams.maxForce,
  72606. collideConnected: !!jointData.collision
  72607. };
  72608. switch (impostorJoint.joint.type) {
  72609. case BABYLON.PhysicsJoint.HingeJoint:
  72610. case BABYLON.PhysicsJoint.Hinge2Joint:
  72611. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  72612. break;
  72613. case BABYLON.PhysicsJoint.DistanceJoint:
  72614. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  72615. break;
  72616. case BABYLON.PhysicsJoint.SpringJoint:
  72617. var springData = jointData;
  72618. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  72619. restLength: springData.length,
  72620. stiffness: springData.stiffness,
  72621. damping: springData.damping,
  72622. localAnchorA: constraintData.pivotA,
  72623. localAnchorB: constraintData.pivotB
  72624. });
  72625. break;
  72626. case BABYLON.PhysicsJoint.LockJoint:
  72627. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  72628. break;
  72629. case BABYLON.PhysicsJoint.PointToPointJoint:
  72630. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72631. default:
  72632. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  72633. break;
  72634. }
  72635. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  72636. constraint.collideConnected = !!jointData.collision;
  72637. impostorJoint.joint.physicsJoint = constraint;
  72638. //don't add spring as constraint, as it is not one.
  72639. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  72640. this.world.addConstraint(constraint);
  72641. }
  72642. else {
  72643. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  72644. constraint.applyForce();
  72645. });
  72646. }
  72647. };
  72648. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72649. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  72650. };
  72651. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  72652. var index;
  72653. var mat;
  72654. for (index = 0; index < this._physicsMaterials.length; index++) {
  72655. mat = this._physicsMaterials[index];
  72656. if (mat.friction === friction && mat.restitution === restitution) {
  72657. return mat;
  72658. }
  72659. }
  72660. var currentMat = new this.BJSCANNON.Material(name);
  72661. currentMat.friction = friction;
  72662. currentMat.restitution = restitution;
  72663. this._physicsMaterials.push(currentMat);
  72664. return currentMat;
  72665. };
  72666. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  72667. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  72668. };
  72669. CannonJSPlugin.prototype._createShape = function (impostor) {
  72670. var object = impostor.object;
  72671. var returnValue;
  72672. var extendSize = impostor.getObjectExtendSize();
  72673. switch (impostor.type) {
  72674. case BABYLON.PhysicsImpostor.SphereImpostor:
  72675. var radiusX = extendSize.x;
  72676. var radiusY = extendSize.y;
  72677. var radiusZ = extendSize.z;
  72678. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  72679. break;
  72680. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  72681. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72682. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  72683. break;
  72684. case BABYLON.PhysicsImpostor.BoxImpostor:
  72685. var box = extendSize.scale(0.5);
  72686. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  72687. break;
  72688. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72689. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  72690. returnValue = new this.BJSCANNON.Plane();
  72691. break;
  72692. case BABYLON.PhysicsImpostor.MeshImpostor:
  72693. // should transform the vertex data to world coordinates!!
  72694. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  72695. var rawFaces = object.getIndices ? object.getIndices() : [];
  72696. if (!rawVerts)
  72697. return;
  72698. // get only scale! so the object could transform correctly.
  72699. var oldPosition = object.position.clone();
  72700. var oldRotation = object.rotation && object.rotation.clone();
  72701. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  72702. object.position.copyFromFloats(0, 0, 0);
  72703. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72704. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72705. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72706. var transform = object.computeWorldMatrix(true);
  72707. // convert rawVerts to object space
  72708. var temp = new Array();
  72709. var index;
  72710. for (index = 0; index < rawVerts.length; index += 3) {
  72711. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  72712. }
  72713. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  72714. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  72715. //now set back the transformation!
  72716. object.position.copyFrom(oldPosition);
  72717. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  72718. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  72719. break;
  72720. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  72721. var oldPosition2 = object.position.clone();
  72722. var oldRotation2 = object.rotation && object.rotation.clone();
  72723. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  72724. object.position.copyFromFloats(0, 0, 0);
  72725. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72726. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72727. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72728. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  72729. returnValue = this._createHeightmap(object);
  72730. object.position.copyFrom(oldPosition2);
  72731. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  72732. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  72733. object.computeWorldMatrix(true);
  72734. break;
  72735. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72736. returnValue = new this.BJSCANNON.Particle();
  72737. break;
  72738. }
  72739. return returnValue;
  72740. };
  72741. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  72742. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  72743. var transform = object.computeWorldMatrix(true);
  72744. // convert rawVerts to object space
  72745. var temp = new Array();
  72746. var index;
  72747. for (index = 0; index < pos.length; index += 3) {
  72748. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  72749. }
  72750. pos = temp;
  72751. var matrix = new Array();
  72752. //For now pointDepth will not be used and will be automatically calculated.
  72753. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  72754. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  72755. var boundingInfo = object.getBoundingInfo();
  72756. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  72757. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  72758. var elementSize = dim * 2 / arraySize;
  72759. for (var i = 0; i < pos.length; i = i + 3) {
  72760. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  72761. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  72762. var y = -pos[i + 2] + minY;
  72763. if (!matrix[x]) {
  72764. matrix[x] = [];
  72765. }
  72766. if (!matrix[x][z]) {
  72767. matrix[x][z] = y;
  72768. }
  72769. matrix[x][z] = Math.max(y, matrix[x][z]);
  72770. }
  72771. for (var x = 0; x <= arraySize; ++x) {
  72772. if (!matrix[x]) {
  72773. var loc = 1;
  72774. while (!matrix[(x + loc) % arraySize]) {
  72775. loc++;
  72776. }
  72777. matrix[x] = matrix[(x + loc) % arraySize].slice();
  72778. //console.log("missing x", x);
  72779. }
  72780. for (var z = 0; z <= arraySize; ++z) {
  72781. if (!matrix[x][z]) {
  72782. var loc = 1;
  72783. var newValue;
  72784. while (newValue === undefined) {
  72785. newValue = matrix[x][(z + loc++) % arraySize];
  72786. }
  72787. matrix[x][z] = newValue;
  72788. }
  72789. }
  72790. }
  72791. var shape = new this.BJSCANNON.Heightfield(matrix, {
  72792. elementSize: elementSize
  72793. });
  72794. //For future reference, needed for body transformation
  72795. shape.minY = minY;
  72796. return shape;
  72797. };
  72798. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  72799. var object = impostor.object;
  72800. //make sure it is updated...
  72801. object.computeWorldMatrix && object.computeWorldMatrix(true);
  72802. // The delta between the mesh position and the mesh bounding box center
  72803. var bInfo = object.getBoundingInfo();
  72804. if (!bInfo)
  72805. return;
  72806. var center = impostor.getObjectCenter();
  72807. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  72808. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  72809. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  72810. this._tmpPosition.copyFrom(center);
  72811. var quaternion = object.rotationQuaternion;
  72812. if (!quaternion) {
  72813. return;
  72814. }
  72815. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  72816. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  72817. //-90 DEG in X, precalculated
  72818. quaternion = quaternion.multiply(this._minus90X);
  72819. //Invert! (Precalculated, 90 deg in X)
  72820. //No need to clone. this will never change.
  72821. impostor.setDeltaRotation(this._plus90X);
  72822. }
  72823. //If it is a heightfield, if should be centered.
  72824. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  72825. var mesh = object;
  72826. var boundingInfo = mesh.getBoundingInfo();
  72827. //calculate the correct body position:
  72828. var rotationQuaternion = mesh.rotationQuaternion;
  72829. mesh.rotationQuaternion = this._tmpUnityRotation;
  72830. mesh.computeWorldMatrix(true);
  72831. //get original center with no rotation
  72832. var c = center.clone();
  72833. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  72834. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  72835. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  72836. mesh.setPivotMatrix(p);
  72837. mesh.computeWorldMatrix(true);
  72838. //calculate the translation
  72839. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  72840. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  72841. //add it inverted to the delta
  72842. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  72843. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  72844. //rotation is back
  72845. mesh.rotationQuaternion = rotationQuaternion;
  72846. mesh.setPivotMatrix(oldPivot);
  72847. mesh.computeWorldMatrix(true);
  72848. }
  72849. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  72850. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  72851. //this._tmpPosition.copyFrom(object.position);
  72852. }
  72853. impostor.setDeltaPosition(this._tmpDeltaPosition);
  72854. //Now update the impostor object
  72855. impostor.physicsBody.position.copy(this._tmpPosition);
  72856. impostor.physicsBody.quaternion.copy(quaternion);
  72857. };
  72858. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72859. impostor.object.position.copyFrom(impostor.physicsBody.position);
  72860. if (impostor.object.rotationQuaternion) {
  72861. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  72862. }
  72863. };
  72864. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72865. impostor.physicsBody.position.copy(newPosition);
  72866. impostor.physicsBody.quaternion.copy(newRotation);
  72867. };
  72868. CannonJSPlugin.prototype.isSupported = function () {
  72869. return this.BJSCANNON !== undefined;
  72870. };
  72871. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72872. impostor.physicsBody.velocity.copy(velocity);
  72873. };
  72874. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72875. impostor.physicsBody.angularVelocity.copy(velocity);
  72876. };
  72877. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72878. var v = impostor.physicsBody.velocity;
  72879. if (!v) {
  72880. return null;
  72881. }
  72882. return new BABYLON.Vector3(v.x, v.y, v.z);
  72883. };
  72884. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72885. var v = impostor.physicsBody.angularVelocity;
  72886. if (!v) {
  72887. return null;
  72888. }
  72889. return new BABYLON.Vector3(v.x, v.y, v.z);
  72890. };
  72891. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72892. impostor.physicsBody.mass = mass;
  72893. impostor.physicsBody.updateMassProperties();
  72894. };
  72895. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  72896. return impostor.physicsBody.mass;
  72897. };
  72898. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  72899. return impostor.physicsBody.material.friction;
  72900. };
  72901. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72902. impostor.physicsBody.material.friction = friction;
  72903. };
  72904. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72905. return impostor.physicsBody.material.restitution;
  72906. };
  72907. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72908. impostor.physicsBody.material.restitution = restitution;
  72909. };
  72910. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  72911. impostor.physicsBody.sleep();
  72912. };
  72913. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  72914. impostor.physicsBody.wakeUp();
  72915. };
  72916. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72917. joint.physicsJoint.distance = maxDistance;
  72918. };
  72919. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72920. // if (!motorIndex) {
  72921. // joint.physicsJoint.enableMotor();
  72922. // }
  72923. // }
  72924. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72925. // if (!motorIndex) {
  72926. // joint.physicsJoint.disableMotor();
  72927. // }
  72928. // }
  72929. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72930. if (!motorIndex) {
  72931. joint.physicsJoint.enableMotor();
  72932. joint.physicsJoint.setMotorSpeed(speed);
  72933. if (maxForce) {
  72934. this.setLimit(joint, maxForce);
  72935. }
  72936. }
  72937. };
  72938. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  72939. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  72940. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  72941. };
  72942. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72943. var body = impostor.physicsBody;
  72944. mesh.position.x = body.position.x;
  72945. mesh.position.y = body.position.y;
  72946. mesh.position.z = body.position.z;
  72947. if (mesh.rotationQuaternion) {
  72948. mesh.rotationQuaternion.x = body.quaternion.x;
  72949. mesh.rotationQuaternion.y = body.quaternion.y;
  72950. mesh.rotationQuaternion.z = body.quaternion.z;
  72951. mesh.rotationQuaternion.w = body.quaternion.w;
  72952. }
  72953. };
  72954. CannonJSPlugin.prototype.getRadius = function (impostor) {
  72955. var shape = impostor.physicsBody.shapes[0];
  72956. return shape.boundingSphereRadius;
  72957. };
  72958. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72959. var shape = impostor.physicsBody.shapes[0];
  72960. result.x = shape.halfExtents.x * 2;
  72961. result.y = shape.halfExtents.y * 2;
  72962. result.z = shape.halfExtents.z * 2;
  72963. };
  72964. CannonJSPlugin.prototype.dispose = function () {
  72965. };
  72966. CannonJSPlugin.prototype._extendNamespace = function () {
  72967. //this will force cannon to execute at least one step when using interpolation
  72968. var step_tmp1 = new this.BJSCANNON.Vec3();
  72969. var Engine = this.BJSCANNON;
  72970. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  72971. maxSubSteps = maxSubSteps || 10;
  72972. timeSinceLastCalled = timeSinceLastCalled || 0;
  72973. if (timeSinceLastCalled === 0) {
  72974. this.internalStep(dt);
  72975. this.time += dt;
  72976. }
  72977. else {
  72978. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  72979. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  72980. var t0 = performance.now();
  72981. for (var i = 0; i !== internalSteps; i++) {
  72982. this.internalStep(dt);
  72983. if (performance.now() - t0 > dt * 1000) {
  72984. break;
  72985. }
  72986. }
  72987. this.time += timeSinceLastCalled;
  72988. var h = this.time % dt;
  72989. var h_div_dt = h / dt;
  72990. var interpvelo = step_tmp1;
  72991. var bodies = this.bodies;
  72992. for (var j = 0; j !== bodies.length; j++) {
  72993. var b = bodies[j];
  72994. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  72995. b.position.vsub(b.previousPosition, interpvelo);
  72996. interpvelo.scale(h_div_dt, interpvelo);
  72997. b.position.vadd(interpvelo, b.interpolatedPosition);
  72998. }
  72999. else {
  73000. b.interpolatedPosition.copy(b.position);
  73001. b.interpolatedQuaternion.copy(b.quaternion);
  73002. }
  73003. }
  73004. }
  73005. };
  73006. };
  73007. return CannonJSPlugin;
  73008. }());
  73009. BABYLON.CannonJSPlugin = CannonJSPlugin;
  73010. })(BABYLON || (BABYLON = {}));
  73011. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  73012. var BABYLON;
  73013. (function (BABYLON) {
  73014. var OimoJSPlugin = /** @class */ (function () {
  73015. function OimoJSPlugin(iterations) {
  73016. this.name = "OimoJSPlugin";
  73017. this._tmpImpostorsArray = [];
  73018. this._tmpPositionVector = BABYLON.Vector3.Zero();
  73019. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  73020. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  73021. this.world.worldscale(1);
  73022. this.world.clear();
  73023. //making sure no stats are calculated
  73024. this.world.isNoStat = true;
  73025. }
  73026. OimoJSPlugin.prototype.setGravity = function (gravity) {
  73027. this.world.gravity.copy(gravity);
  73028. };
  73029. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  73030. this.world.timeStep = timeStep;
  73031. };
  73032. OimoJSPlugin.prototype.getTimeStep = function () {
  73033. return this.world.timeStep;
  73034. };
  73035. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  73036. var _this = this;
  73037. impostors.forEach(function (impostor) {
  73038. impostor.beforeStep();
  73039. });
  73040. this.world.step();
  73041. impostors.forEach(function (impostor) {
  73042. impostor.afterStep();
  73043. //update the ordered impostors array
  73044. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  73045. });
  73046. //check for collisions
  73047. var contact = this.world.contacts;
  73048. while (contact !== null) {
  73049. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  73050. contact = contact.next;
  73051. continue;
  73052. }
  73053. //is this body colliding with any other? get the impostor
  73054. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  73055. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  73056. if (!mainImpostor || !collidingImpostor) {
  73057. contact = contact.next;
  73058. continue;
  73059. }
  73060. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  73061. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  73062. contact = contact.next;
  73063. }
  73064. };
  73065. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  73066. var mass = impostor.physicsBody.massInfo.mass;
  73067. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  73068. };
  73069. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  73070. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  73071. this.applyImpulse(impostor, force, contactPoint);
  73072. };
  73073. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  73074. var _this = this;
  73075. //parent-child relationship. Does this impostor has a parent impostor?
  73076. if (impostor.parent) {
  73077. if (impostor.physicsBody) {
  73078. this.removePhysicsBody(impostor);
  73079. //TODO is that needed?
  73080. impostor.forceUpdate();
  73081. }
  73082. return;
  73083. }
  73084. if (impostor.isBodyInitRequired()) {
  73085. var bodyConfig = {
  73086. name: impostor.uniqueId,
  73087. //Oimo must have mass, also for static objects.
  73088. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  73089. size: [],
  73090. type: [],
  73091. pos: [],
  73092. rot: [],
  73093. move: impostor.getParam("mass") !== 0,
  73094. //Supporting older versions of Oimo
  73095. world: this.world
  73096. };
  73097. var impostors = [impostor];
  73098. var addToArray = function (parent) {
  73099. if (!parent.getChildMeshes)
  73100. return;
  73101. parent.getChildMeshes().forEach(function (m) {
  73102. if (m.physicsImpostor) {
  73103. impostors.push(m.physicsImpostor);
  73104. //m.physicsImpostor._init();
  73105. }
  73106. });
  73107. };
  73108. addToArray(impostor.object);
  73109. var checkWithEpsilon_1 = function (value) {
  73110. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  73111. };
  73112. impostors.forEach(function (i) {
  73113. if (!impostor.object.rotationQuaternion) {
  73114. return;
  73115. }
  73116. //get the correct bounding box
  73117. var oldQuaternion = i.object.rotationQuaternion;
  73118. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  73119. x: impostor.object.rotationQuaternion.x,
  73120. y: impostor.object.rotationQuaternion.y,
  73121. z: impostor.object.rotationQuaternion.z,
  73122. s: impostor.object.rotationQuaternion.w
  73123. });
  73124. var extendSize = i.getObjectExtendSize();
  73125. if (i === impostor) {
  73126. var center = impostor.getObjectCenter();
  73127. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  73128. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  73129. //Can also use Array.prototype.push.apply
  73130. bodyConfig.pos.push(center.x);
  73131. bodyConfig.pos.push(center.y);
  73132. bodyConfig.pos.push(center.z);
  73133. //tmp solution
  73134. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73135. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73136. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73137. }
  73138. else {
  73139. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  73140. bodyConfig.pos.push(localPosition.x);
  73141. bodyConfig.pos.push(localPosition.y);
  73142. bodyConfig.pos.push(localPosition.z);
  73143. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  73144. bodyConfig.rot.push(0);
  73145. bodyConfig.rot.push(0);
  73146. bodyConfig.rot.push(0);
  73147. }
  73148. // register mesh
  73149. switch (i.type) {
  73150. case BABYLON.PhysicsImpostor.ParticleImpostor:
  73151. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  73152. case BABYLON.PhysicsImpostor.SphereImpostor:
  73153. var radiusX = extendSize.x;
  73154. var radiusY = extendSize.y;
  73155. var radiusZ = extendSize.z;
  73156. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  73157. bodyConfig.type.push('sphere');
  73158. //due to the way oimo works with compounds, add 3 times
  73159. bodyConfig.size.push(size);
  73160. bodyConfig.size.push(size);
  73161. bodyConfig.size.push(size);
  73162. break;
  73163. case BABYLON.PhysicsImpostor.CylinderImpostor:
  73164. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  73165. var sizeY = checkWithEpsilon_1(extendSize.y);
  73166. bodyConfig.type.push('cylinder');
  73167. bodyConfig.size.push(sizeX);
  73168. bodyConfig.size.push(sizeY);
  73169. //due to the way oimo works with compounds, add one more value.
  73170. bodyConfig.size.push(sizeY);
  73171. break;
  73172. case BABYLON.PhysicsImpostor.PlaneImpostor:
  73173. case BABYLON.PhysicsImpostor.BoxImpostor:
  73174. default:
  73175. var sizeX = checkWithEpsilon_1(extendSize.x);
  73176. var sizeY = checkWithEpsilon_1(extendSize.y);
  73177. var sizeZ = checkWithEpsilon_1(extendSize.z);
  73178. bodyConfig.type.push('box');
  73179. bodyConfig.size.push(sizeX);
  73180. bodyConfig.size.push(sizeY);
  73181. bodyConfig.size.push(sizeZ);
  73182. break;
  73183. }
  73184. //actually not needed, but hey...
  73185. i.object.rotationQuaternion = oldQuaternion;
  73186. });
  73187. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  73188. }
  73189. else {
  73190. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  73191. }
  73192. impostor.setDeltaPosition(this._tmpPositionVector);
  73193. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  73194. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  73195. };
  73196. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  73197. //impostor.physicsBody.dispose();
  73198. //Same as : (older oimo versions)
  73199. this.world.removeRigidBody(impostor.physicsBody);
  73200. };
  73201. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  73202. var mainBody = impostorJoint.mainImpostor.physicsBody;
  73203. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  73204. if (!mainBody || !connectedBody) {
  73205. return;
  73206. }
  73207. var jointData = impostorJoint.joint.jointData;
  73208. var options = jointData.nativeParams || {};
  73209. var type;
  73210. var nativeJointData = {
  73211. body1: mainBody,
  73212. body2: connectedBody,
  73213. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  73214. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  73215. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  73216. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  73217. min: options.min,
  73218. max: options.max,
  73219. collision: options.collision || jointData.collision,
  73220. spring: options.spring,
  73221. //supporting older version of Oimo
  73222. world: this.world
  73223. };
  73224. switch (impostorJoint.joint.type) {
  73225. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  73226. type = "jointBall";
  73227. break;
  73228. case BABYLON.PhysicsJoint.SpringJoint:
  73229. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  73230. var springData = jointData;
  73231. nativeJointData.min = springData.length || nativeJointData.min;
  73232. //Max should also be set, just make sure it is at least min
  73233. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  73234. case BABYLON.PhysicsJoint.DistanceJoint:
  73235. type = "jointDistance";
  73236. nativeJointData.max = jointData.maxDistance;
  73237. break;
  73238. case BABYLON.PhysicsJoint.PrismaticJoint:
  73239. type = "jointPrisme";
  73240. break;
  73241. case BABYLON.PhysicsJoint.SliderJoint:
  73242. type = "jointSlide";
  73243. break;
  73244. case BABYLON.PhysicsJoint.WheelJoint:
  73245. type = "jointWheel";
  73246. break;
  73247. case BABYLON.PhysicsJoint.HingeJoint:
  73248. default:
  73249. type = "jointHinge";
  73250. break;
  73251. }
  73252. nativeJointData.type = type;
  73253. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  73254. };
  73255. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  73256. //Bug in Oimo prevents us from disposing a joint in the playground
  73257. //joint.joint.physicsJoint.dispose();
  73258. //So we will bruteforce it!
  73259. try {
  73260. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  73261. }
  73262. catch (e) {
  73263. BABYLON.Tools.Warn(e);
  73264. }
  73265. };
  73266. OimoJSPlugin.prototype.isSupported = function () {
  73267. return this.BJSOIMO !== undefined;
  73268. };
  73269. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73270. if (!impostor.physicsBody.sleeping) {
  73271. //TODO check that
  73272. if (impostor.physicsBody.shapes.next) {
  73273. var parentShape = this._getLastShape(impostor.physicsBody);
  73274. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  73275. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  73276. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  73277. }
  73278. else {
  73279. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  73280. }
  73281. if (impostor.object.rotationQuaternion) {
  73282. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  73283. impostor.object.rotationQuaternion.normalize();
  73284. }
  73285. }
  73286. };
  73287. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73288. var body = impostor.physicsBody;
  73289. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  73290. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  73291. body.syncShapes();
  73292. body.awake();
  73293. };
  73294. OimoJSPlugin.prototype._getLastShape = function (body) {
  73295. var lastShape = body.shapes;
  73296. while (lastShape.next) {
  73297. lastShape = lastShape.next;
  73298. }
  73299. return lastShape;
  73300. };
  73301. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73302. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  73303. };
  73304. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73305. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  73306. };
  73307. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73308. var v = impostor.physicsBody.linearVelocity;
  73309. if (!v) {
  73310. return null;
  73311. }
  73312. return new BABYLON.Vector3(v.x, v.y, v.z);
  73313. };
  73314. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73315. var v = impostor.physicsBody.angularVelocity;
  73316. if (!v) {
  73317. return null;
  73318. }
  73319. return new BABYLON.Vector3(v.x, v.y, v.z);
  73320. };
  73321. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73322. var staticBody = mass === 0;
  73323. //this will actually set the body's density and not its mass.
  73324. //But this is how oimo treats the mass variable.
  73325. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  73326. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  73327. };
  73328. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  73329. return impostor.physicsBody.shapes.density;
  73330. };
  73331. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  73332. return impostor.physicsBody.shapes.friction;
  73333. };
  73334. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73335. impostor.physicsBody.shapes.friction = friction;
  73336. };
  73337. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73338. return impostor.physicsBody.shapes.restitution;
  73339. };
  73340. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73341. impostor.physicsBody.shapes.restitution = restitution;
  73342. };
  73343. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  73344. impostor.physicsBody.sleep();
  73345. };
  73346. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  73347. impostor.physicsBody.awake();
  73348. };
  73349. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73350. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  73351. if (minDistance !== void 0) {
  73352. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  73353. }
  73354. };
  73355. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73356. //TODO separate rotational and transational motors.
  73357. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73358. if (motor) {
  73359. motor.setMotor(speed, maxForce);
  73360. }
  73361. };
  73362. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  73363. //TODO separate rotational and transational motors.
  73364. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73365. if (motor) {
  73366. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  73367. }
  73368. };
  73369. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73370. var body = impostor.physicsBody;
  73371. mesh.position.x = body.position.x;
  73372. mesh.position.y = body.position.y;
  73373. mesh.position.z = body.position.z;
  73374. if (mesh.rotationQuaternion) {
  73375. mesh.rotationQuaternion.x = body.orientation.x;
  73376. mesh.rotationQuaternion.y = body.orientation.y;
  73377. mesh.rotationQuaternion.z = body.orientation.z;
  73378. mesh.rotationQuaternion.w = body.orientation.s;
  73379. }
  73380. };
  73381. OimoJSPlugin.prototype.getRadius = function (impostor) {
  73382. return impostor.physicsBody.shapes.radius;
  73383. };
  73384. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73385. var shape = impostor.physicsBody.shapes;
  73386. result.x = shape.halfWidth * 2;
  73387. result.y = shape.halfHeight * 2;
  73388. result.z = shape.halfDepth * 2;
  73389. };
  73390. OimoJSPlugin.prototype.dispose = function () {
  73391. this.world.clear();
  73392. };
  73393. return OimoJSPlugin;
  73394. }());
  73395. BABYLON.OimoJSPlugin = OimoJSPlugin;
  73396. })(BABYLON || (BABYLON = {}));
  73397. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  73398. var BABYLON;
  73399. (function (BABYLON) {
  73400. /*
  73401. * Based on jsTGALoader - Javascript loader for TGA file
  73402. * By Vincent Thibault
  73403. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  73404. */
  73405. var TGATools = /** @class */ (function () {
  73406. function TGATools() {
  73407. }
  73408. TGATools.GetTGAHeader = function (data) {
  73409. var offset = 0;
  73410. var header = {
  73411. id_length: data[offset++],
  73412. colormap_type: data[offset++],
  73413. image_type: data[offset++],
  73414. colormap_index: data[offset++] | data[offset++] << 8,
  73415. colormap_length: data[offset++] | data[offset++] << 8,
  73416. colormap_size: data[offset++],
  73417. origin: [
  73418. data[offset++] | data[offset++] << 8,
  73419. data[offset++] | data[offset++] << 8
  73420. ],
  73421. width: data[offset++] | data[offset++] << 8,
  73422. height: data[offset++] | data[offset++] << 8,
  73423. pixel_size: data[offset++],
  73424. flags: data[offset++]
  73425. };
  73426. return header;
  73427. };
  73428. TGATools.UploadContent = function (gl, data) {
  73429. // Not enough data to contain header ?
  73430. if (data.length < 19) {
  73431. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  73432. return;
  73433. }
  73434. // Read Header
  73435. var offset = 18;
  73436. var header = TGATools.GetTGAHeader(data);
  73437. // Assume it's a valid Targa file.
  73438. if (header.id_length + offset > data.length) {
  73439. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  73440. return;
  73441. }
  73442. // Skip not needed data
  73443. offset += header.id_length;
  73444. var use_rle = false;
  73445. var use_pal = false;
  73446. var use_grey = false;
  73447. // Get some informations.
  73448. switch (header.image_type) {
  73449. case TGATools._TYPE_RLE_INDEXED:
  73450. use_rle = true;
  73451. case TGATools._TYPE_INDEXED:
  73452. use_pal = true;
  73453. break;
  73454. case TGATools._TYPE_RLE_RGB:
  73455. use_rle = true;
  73456. case TGATools._TYPE_RGB:
  73457. // use_rgb = true;
  73458. break;
  73459. case TGATools._TYPE_RLE_GREY:
  73460. use_rle = true;
  73461. case TGATools._TYPE_GREY:
  73462. use_grey = true;
  73463. break;
  73464. }
  73465. var pixel_data;
  73466. // var numAlphaBits = header.flags & 0xf;
  73467. var pixel_size = header.pixel_size >> 3;
  73468. var pixel_total = header.width * header.height * pixel_size;
  73469. // Read palettes
  73470. var palettes;
  73471. if (use_pal) {
  73472. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  73473. }
  73474. // Read LRE
  73475. if (use_rle) {
  73476. pixel_data = new Uint8Array(pixel_total);
  73477. var c, count, i;
  73478. var localOffset = 0;
  73479. var pixels = new Uint8Array(pixel_size);
  73480. while (offset < pixel_total && localOffset < pixel_total) {
  73481. c = data[offset++];
  73482. count = (c & 0x7f) + 1;
  73483. // RLE pixels
  73484. if (c & 0x80) {
  73485. // Bind pixel tmp array
  73486. for (i = 0; i < pixel_size; ++i) {
  73487. pixels[i] = data[offset++];
  73488. }
  73489. // Copy pixel array
  73490. for (i = 0; i < count; ++i) {
  73491. pixel_data.set(pixels, localOffset + i * pixel_size);
  73492. }
  73493. localOffset += pixel_size * count;
  73494. }
  73495. else {
  73496. count *= pixel_size;
  73497. for (i = 0; i < count; ++i) {
  73498. pixel_data[localOffset + i] = data[offset++];
  73499. }
  73500. localOffset += count;
  73501. }
  73502. }
  73503. }
  73504. else {
  73505. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  73506. }
  73507. // Load to texture
  73508. var x_start, y_start, x_step, y_step, y_end, x_end;
  73509. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  73510. default:
  73511. case TGATools._ORIGIN_UL:
  73512. x_start = 0;
  73513. x_step = 1;
  73514. x_end = header.width;
  73515. y_start = 0;
  73516. y_step = 1;
  73517. y_end = header.height;
  73518. break;
  73519. case TGATools._ORIGIN_BL:
  73520. x_start = 0;
  73521. x_step = 1;
  73522. x_end = header.width;
  73523. y_start = header.height - 1;
  73524. y_step = -1;
  73525. y_end = -1;
  73526. break;
  73527. case TGATools._ORIGIN_UR:
  73528. x_start = header.width - 1;
  73529. x_step = -1;
  73530. x_end = -1;
  73531. y_start = 0;
  73532. y_step = 1;
  73533. y_end = header.height;
  73534. break;
  73535. case TGATools._ORIGIN_BR:
  73536. x_start = header.width - 1;
  73537. x_step = -1;
  73538. x_end = -1;
  73539. y_start = header.height - 1;
  73540. y_step = -1;
  73541. y_end = -1;
  73542. break;
  73543. }
  73544. // Load the specify method
  73545. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  73546. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  73547. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  73548. };
  73549. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73550. var image = pixel_data, colormap = palettes;
  73551. var width = header.width, height = header.height;
  73552. var color, i = 0, x, y;
  73553. var imageData = new Uint8Array(width * height * 4);
  73554. for (y = y_start; y !== y_end; y += y_step) {
  73555. for (x = x_start; x !== x_end; x += x_step, i++) {
  73556. color = image[i];
  73557. imageData[(x + width * y) * 4 + 3] = 255;
  73558. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  73559. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  73560. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  73561. }
  73562. }
  73563. return imageData;
  73564. };
  73565. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73566. var image = pixel_data;
  73567. var width = header.width, height = header.height;
  73568. var color, i = 0, x, y;
  73569. var imageData = new Uint8Array(width * height * 4);
  73570. for (y = y_start; y !== y_end; y += y_step) {
  73571. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73572. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  73573. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  73574. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  73575. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  73576. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  73577. }
  73578. }
  73579. return imageData;
  73580. };
  73581. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73582. var image = pixel_data;
  73583. var width = header.width, height = header.height;
  73584. var i = 0, x, y;
  73585. var imageData = new Uint8Array(width * height * 4);
  73586. for (y = y_start; y !== y_end; y += y_step) {
  73587. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  73588. imageData[(x + width * y) * 4 + 3] = 255;
  73589. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73590. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73591. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73592. }
  73593. }
  73594. return imageData;
  73595. };
  73596. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73597. var image = pixel_data;
  73598. var width = header.width, height = header.height;
  73599. var i = 0, x, y;
  73600. var imageData = new Uint8Array(width * height * 4);
  73601. for (y = y_start; y !== y_end; y += y_step) {
  73602. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  73603. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73604. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73605. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73606. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  73607. }
  73608. }
  73609. return imageData;
  73610. };
  73611. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73612. var image = pixel_data;
  73613. var width = header.width, height = header.height;
  73614. var color, i = 0, x, y;
  73615. var imageData = new Uint8Array(width * height * 4);
  73616. for (y = y_start; y !== y_end; y += y_step) {
  73617. for (x = x_start; x !== x_end; x += x_step, i++) {
  73618. color = image[i];
  73619. imageData[(x + width * y) * 4 + 0] = color;
  73620. imageData[(x + width * y) * 4 + 1] = color;
  73621. imageData[(x + width * y) * 4 + 2] = color;
  73622. imageData[(x + width * y) * 4 + 3] = 255;
  73623. }
  73624. }
  73625. return imageData;
  73626. };
  73627. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73628. var image = pixel_data;
  73629. var width = header.width, height = header.height;
  73630. var i = 0, x, y;
  73631. var imageData = new Uint8Array(width * height * 4);
  73632. for (y = y_start; y !== y_end; y += y_step) {
  73633. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73634. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  73635. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  73636. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73637. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  73638. }
  73639. }
  73640. return imageData;
  73641. };
  73642. //private static _TYPE_NO_DATA = 0;
  73643. TGATools._TYPE_INDEXED = 1;
  73644. TGATools._TYPE_RGB = 2;
  73645. TGATools._TYPE_GREY = 3;
  73646. TGATools._TYPE_RLE_INDEXED = 9;
  73647. TGATools._TYPE_RLE_RGB = 10;
  73648. TGATools._TYPE_RLE_GREY = 11;
  73649. TGATools._ORIGIN_MASK = 0x30;
  73650. TGATools._ORIGIN_SHIFT = 0x04;
  73651. TGATools._ORIGIN_BL = 0x00;
  73652. TGATools._ORIGIN_BR = 0x01;
  73653. TGATools._ORIGIN_UL = 0x02;
  73654. TGATools._ORIGIN_UR = 0x03;
  73655. return TGATools;
  73656. }());
  73657. BABYLON.TGATools = TGATools;
  73658. })(BABYLON || (BABYLON = {}));
  73659. //# sourceMappingURL=babylon.tga.js.map
  73660. var BABYLON;
  73661. (function (BABYLON) {
  73662. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  73663. // All values and structures referenced from:
  73664. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  73665. var DDS_MAGIC = 0x20534444;
  73666. var
  73667. //DDSD_CAPS = 0x1,
  73668. //DDSD_HEIGHT = 0x2,
  73669. //DDSD_WIDTH = 0x4,
  73670. //DDSD_PITCH = 0x8,
  73671. //DDSD_PIXELFORMAT = 0x1000,
  73672. DDSD_MIPMAPCOUNT = 0x20000;
  73673. //DDSD_LINEARSIZE = 0x80000,
  73674. //DDSD_DEPTH = 0x800000;
  73675. // var DDSCAPS_COMPLEX = 0x8,
  73676. // DDSCAPS_MIPMAP = 0x400000,
  73677. // DDSCAPS_TEXTURE = 0x1000;
  73678. var DDSCAPS2_CUBEMAP = 0x200;
  73679. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  73680. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  73681. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  73682. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  73683. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  73684. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  73685. // DDSCAPS2_VOLUME = 0x200000;
  73686. var
  73687. //DDPF_ALPHAPIXELS = 0x1,
  73688. //DDPF_ALPHA = 0x2,
  73689. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  73690. //DDPF_YUV = 0x200,
  73691. DDPF_LUMINANCE = 0x20000;
  73692. function FourCCToInt32(value) {
  73693. return value.charCodeAt(0) +
  73694. (value.charCodeAt(1) << 8) +
  73695. (value.charCodeAt(2) << 16) +
  73696. (value.charCodeAt(3) << 24);
  73697. }
  73698. function Int32ToFourCC(value) {
  73699. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  73700. }
  73701. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  73702. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  73703. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  73704. var FOURCC_DX10 = FourCCToInt32("DX10");
  73705. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  73706. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  73707. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  73708. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  73709. var headerLengthInt = 31; // The header length in 32 bit ints
  73710. // Offsets into the header array
  73711. var off_magic = 0;
  73712. var off_size = 1;
  73713. var off_flags = 2;
  73714. var off_height = 3;
  73715. var off_width = 4;
  73716. var off_mipmapCount = 7;
  73717. var off_pfFlags = 20;
  73718. var off_pfFourCC = 21;
  73719. var off_RGBbpp = 22;
  73720. var off_RMask = 23;
  73721. var off_GMask = 24;
  73722. var off_BMask = 25;
  73723. var off_AMask = 26;
  73724. // var off_caps1 = 27;
  73725. var off_caps2 = 28;
  73726. // var off_caps3 = 29;
  73727. // var off_caps4 = 30;
  73728. var off_dxgiFormat = 32;
  73729. ;
  73730. var DDSTools = /** @class */ (function () {
  73731. function DDSTools() {
  73732. }
  73733. DDSTools.GetDDSInfo = function (arrayBuffer) {
  73734. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73735. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  73736. var mipmapCount = 1;
  73737. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  73738. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73739. }
  73740. var fourCC = header[off_pfFourCC];
  73741. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  73742. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73743. switch (fourCC) {
  73744. case FOURCC_D3DFMT_R16G16B16A16F:
  73745. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73746. break;
  73747. case FOURCC_D3DFMT_R32G32B32A32F:
  73748. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73749. break;
  73750. case FOURCC_DX10:
  73751. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  73752. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73753. break;
  73754. }
  73755. }
  73756. return {
  73757. width: header[off_width],
  73758. height: header[off_height],
  73759. mipmapCount: mipmapCount,
  73760. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  73761. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  73762. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  73763. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  73764. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  73765. dxgiFormat: dxgiFormat,
  73766. textureType: textureType
  73767. };
  73768. };
  73769. DDSTools._ToHalfFloat = function (value) {
  73770. if (!DDSTools._FloatView) {
  73771. DDSTools._FloatView = new Float32Array(1);
  73772. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  73773. }
  73774. DDSTools._FloatView[0] = value;
  73775. var x = DDSTools._Int32View[0];
  73776. var bits = (x >> 16) & 0x8000; /* Get the sign */
  73777. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  73778. var e = (x >> 23) & 0xff; /* Using int is faster here */
  73779. /* If zero, or denormal, or exponent underflows too much for a denormal
  73780. * half, return signed zero. */
  73781. if (e < 103) {
  73782. return bits;
  73783. }
  73784. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  73785. if (e > 142) {
  73786. bits |= 0x7c00;
  73787. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  73788. * not Inf, so make sure we set one mantissa bit too. */
  73789. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  73790. return bits;
  73791. }
  73792. /* If exponent underflows but not too much, return a denormal */
  73793. if (e < 113) {
  73794. m |= 0x0800;
  73795. /* Extra rounding may overflow and set mantissa to 0 and exponent
  73796. * to 1, which is OK. */
  73797. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  73798. return bits;
  73799. }
  73800. bits |= ((e - 112) << 10) | (m >> 1);
  73801. bits += m & 1;
  73802. return bits;
  73803. };
  73804. DDSTools._FromHalfFloat = function (value) {
  73805. var s = (value & 0x8000) >> 15;
  73806. var e = (value & 0x7C00) >> 10;
  73807. var f = value & 0x03FF;
  73808. if (e === 0) {
  73809. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  73810. }
  73811. else if (e == 0x1F) {
  73812. return f ? NaN : ((s ? -1 : 1) * Infinity);
  73813. }
  73814. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  73815. };
  73816. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73817. var destArray = new Float32Array(dataLength);
  73818. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73819. var index = 0;
  73820. for (var y = 0; y < height; y++) {
  73821. for (var x = 0; x < width; x++) {
  73822. var srcPos = (x + y * width) * 4;
  73823. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  73824. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  73825. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  73826. if (DDSTools.StoreLODInAlphaChannel) {
  73827. destArray[index + 3] = lod;
  73828. }
  73829. else {
  73830. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  73831. }
  73832. index += 4;
  73833. }
  73834. }
  73835. return destArray;
  73836. };
  73837. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73838. if (DDSTools.StoreLODInAlphaChannel) {
  73839. var destArray = new Uint16Array(dataLength);
  73840. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73841. var index = 0;
  73842. for (var y = 0; y < height; y++) {
  73843. for (var x = 0; x < width; x++) {
  73844. var srcPos = (x + y * width) * 4;
  73845. destArray[index] = srcData[srcPos];
  73846. destArray[index + 1] = srcData[srcPos + 1];
  73847. destArray[index + 2] = srcData[srcPos + 2];
  73848. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  73849. index += 4;
  73850. }
  73851. }
  73852. return destArray;
  73853. }
  73854. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  73855. };
  73856. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73857. if (DDSTools.StoreLODInAlphaChannel) {
  73858. var destArray = new Float32Array(dataLength);
  73859. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73860. var index = 0;
  73861. for (var y = 0; y < height; y++) {
  73862. for (var x = 0; x < width; x++) {
  73863. var srcPos = (x + y * width) * 4;
  73864. destArray[index] = srcData[srcPos];
  73865. destArray[index + 1] = srcData[srcPos + 1];
  73866. destArray[index + 2] = srcData[srcPos + 2];
  73867. destArray[index + 3] = lod;
  73868. index += 4;
  73869. }
  73870. }
  73871. return destArray;
  73872. }
  73873. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  73874. };
  73875. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73876. var destArray = new Uint8Array(dataLength);
  73877. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73878. var index = 0;
  73879. for (var y = 0; y < height; y++) {
  73880. for (var x = 0; x < width; x++) {
  73881. var srcPos = (x + y * width) * 4;
  73882. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  73883. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  73884. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  73885. if (DDSTools.StoreLODInAlphaChannel) {
  73886. destArray[index + 3] = lod;
  73887. }
  73888. else {
  73889. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  73890. }
  73891. index += 4;
  73892. }
  73893. }
  73894. return destArray;
  73895. };
  73896. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73897. var destArray = new Uint8Array(dataLength);
  73898. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73899. var index = 0;
  73900. for (var y = 0; y < height; y++) {
  73901. for (var x = 0; x < width; x++) {
  73902. var srcPos = (x + y * width) * 4;
  73903. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  73904. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  73905. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  73906. if (DDSTools.StoreLODInAlphaChannel) {
  73907. destArray[index + 3] = lod;
  73908. }
  73909. else {
  73910. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  73911. }
  73912. index += 4;
  73913. }
  73914. }
  73915. return destArray;
  73916. };
  73917. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  73918. var byteArray = new Uint8Array(dataLength);
  73919. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73920. var index = 0;
  73921. for (var y = 0; y < height; y++) {
  73922. for (var x = 0; x < width; x++) {
  73923. var srcPos = (x + y * width) * 4;
  73924. byteArray[index] = srcData[srcPos + rOffset];
  73925. byteArray[index + 1] = srcData[srcPos + gOffset];
  73926. byteArray[index + 2] = srcData[srcPos + bOffset];
  73927. byteArray[index + 3] = srcData[srcPos + aOffset];
  73928. index += 4;
  73929. }
  73930. }
  73931. return byteArray;
  73932. };
  73933. DDSTools._ExtractLongWordOrder = function (value) {
  73934. if (value === 0 || value === 255 || value === -16777216) {
  73935. return 0;
  73936. }
  73937. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  73938. };
  73939. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  73940. var byteArray = new Uint8Array(dataLength);
  73941. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73942. var index = 0;
  73943. for (var y = 0; y < height; y++) {
  73944. for (var x = 0; x < width; x++) {
  73945. var srcPos = (x + y * width) * 3;
  73946. byteArray[index] = srcData[srcPos + rOffset];
  73947. byteArray[index + 1] = srcData[srcPos + gOffset];
  73948. byteArray[index + 2] = srcData[srcPos + bOffset];
  73949. index += 3;
  73950. }
  73951. }
  73952. return byteArray;
  73953. };
  73954. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  73955. var byteArray = new Uint8Array(dataLength);
  73956. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73957. var index = 0;
  73958. for (var y = 0; y < height; y++) {
  73959. for (var x = 0; x < width; x++) {
  73960. var srcPos = (x + y * width);
  73961. byteArray[index] = srcData[srcPos];
  73962. index++;
  73963. }
  73964. }
  73965. return byteArray;
  73966. };
  73967. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  73968. if (lodIndex === void 0) { lodIndex = -1; }
  73969. var ext = engine.getCaps().s3tc;
  73970. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73971. var fourCC, width, height, dataLength = 0, dataOffset;
  73972. var byteArray, mipmapCount, mip;
  73973. var internalFormat = 0;
  73974. var format = 0;
  73975. var blockBytes = 1;
  73976. if (header[off_magic] !== DDS_MAGIC) {
  73977. BABYLON.Tools.Error("Invalid magic number in DDS header");
  73978. return;
  73979. }
  73980. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  73981. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  73982. return;
  73983. }
  73984. if (info.isCompressed && !ext) {
  73985. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  73986. return;
  73987. }
  73988. var bpp = header[off_RGBbpp];
  73989. dataOffset = header[off_size] + 4;
  73990. var computeFormats = false;
  73991. if (info.isFourCC) {
  73992. fourCC = header[off_pfFourCC];
  73993. switch (fourCC) {
  73994. case FOURCC_DXT1:
  73995. blockBytes = 8;
  73996. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  73997. break;
  73998. case FOURCC_DXT3:
  73999. blockBytes = 16;
  74000. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  74001. break;
  74002. case FOURCC_DXT5:
  74003. blockBytes = 16;
  74004. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  74005. break;
  74006. case FOURCC_D3DFMT_R16G16B16A16F:
  74007. computeFormats = true;
  74008. break;
  74009. case FOURCC_D3DFMT_R32G32B32A32F:
  74010. computeFormats = true;
  74011. break;
  74012. case FOURCC_DX10:
  74013. // There is an additionnal header so dataOffset need to be changed
  74014. dataOffset += 5 * 4; // 5 uints
  74015. var supported = false;
  74016. switch (info.dxgiFormat) {
  74017. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  74018. computeFormats = true;
  74019. supported = true;
  74020. break;
  74021. case DXGI_FORMAT_B8G8R8X8_UNORM:
  74022. info.isRGB = true;
  74023. info.isFourCC = false;
  74024. bpp = 32;
  74025. supported = true;
  74026. break;
  74027. }
  74028. if (supported) {
  74029. break;
  74030. }
  74031. default:
  74032. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  74033. return;
  74034. }
  74035. }
  74036. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  74037. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  74038. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  74039. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  74040. if (computeFormats) {
  74041. format = engine._getWebGLTextureType(info.textureType);
  74042. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74043. }
  74044. mipmapCount = 1;
  74045. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  74046. mipmapCount = Math.max(1, header[off_mipmapCount]);
  74047. }
  74048. for (var face = 0; face < faces; face++) {
  74049. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  74050. width = header[off_width];
  74051. height = header[off_height];
  74052. for (mip = 0; mip < mipmapCount; ++mip) {
  74053. if (lodIndex === -1 || lodIndex === mip) {
  74054. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  74055. var i = (lodIndex === -1) ? mip : 0;
  74056. if (!info.isCompressed && info.isFourCC) {
  74057. dataLength = width * height * 4;
  74058. var floatArray = null;
  74059. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  74060. if (bpp === 128) {
  74061. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74062. }
  74063. else if (bpp === 64) {
  74064. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74065. }
  74066. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74067. format = engine._getWebGLTextureType(info.textureType);
  74068. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74069. }
  74070. else {
  74071. if (bpp === 128) {
  74072. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74073. }
  74074. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  74075. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74076. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74077. format = engine._getWebGLTextureType(info.textureType);
  74078. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74079. }
  74080. else {
  74081. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74082. }
  74083. }
  74084. if (floatArray) {
  74085. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  74086. }
  74087. }
  74088. else if (info.isRGB) {
  74089. if (bpp === 24) {
  74090. dataLength = width * height * 3;
  74091. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  74092. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  74093. }
  74094. else {
  74095. dataLength = width * height * 4;
  74096. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  74097. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  74098. }
  74099. }
  74100. else if (info.isLuminance) {
  74101. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  74102. var unpaddedRowSize = width;
  74103. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  74104. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  74105. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  74106. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  74107. }
  74108. else {
  74109. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  74110. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  74111. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  74112. }
  74113. }
  74114. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  74115. width *= 0.5;
  74116. height *= 0.5;
  74117. width = Math.max(1.0, width);
  74118. height = Math.max(1.0, height);
  74119. }
  74120. if (currentFace !== undefined) {
  74121. // Loading a single face
  74122. break;
  74123. }
  74124. }
  74125. };
  74126. DDSTools.StoreLODInAlphaChannel = false;
  74127. return DDSTools;
  74128. }());
  74129. BABYLON.DDSTools = DDSTools;
  74130. })(BABYLON || (BABYLON = {}));
  74131. //# sourceMappingURL=babylon.dds.js.map
  74132. var BABYLON;
  74133. (function (BABYLON) {
  74134. /**
  74135. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  74136. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  74137. */
  74138. var KhronosTextureContainer = /** @class */ (function () {
  74139. /**
  74140. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  74141. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  74142. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  74143. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  74144. */
  74145. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  74146. this.arrayBuffer = arrayBuffer;
  74147. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  74148. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  74149. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  74150. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  74151. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  74152. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  74153. BABYLON.Tools.Error("texture missing KTX identifier");
  74154. return;
  74155. }
  74156. // load the reset of the header in native 32 bit int
  74157. var header = new Int32Array(this.arrayBuffer, 12, 13);
  74158. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  74159. var oppositeEndianess = header[0] === 0x01020304;
  74160. // read all the header elements in order they exist in the file, without modification (sans endainness)
  74161. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  74162. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  74163. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  74164. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  74165. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  74166. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  74167. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  74168. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  74169. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  74170. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  74171. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  74172. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  74173. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  74174. if (this.glType !== 0) {
  74175. BABYLON.Tools.Error("only compressed formats currently supported");
  74176. return;
  74177. }
  74178. else {
  74179. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  74180. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  74181. }
  74182. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  74183. BABYLON.Tools.Error("only 2D textures currently supported");
  74184. return;
  74185. }
  74186. if (this.numberOfArrayElements !== 0) {
  74187. BABYLON.Tools.Error("texture arrays not currently supported");
  74188. return;
  74189. }
  74190. if (this.numberOfFaces !== facesExpected) {
  74191. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  74192. return;
  74193. }
  74194. // we now have a completely validated file, so could use existence of loadType as success
  74195. // would need to make this more elaborate & adjust checks above to support more than one load type
  74196. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  74197. }
  74198. // not as fast hardware based, but will probably never need to use
  74199. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  74200. return ((val & 0xFF) << 24)
  74201. | ((val & 0xFF00) << 8)
  74202. | ((val >> 8) & 0xFF00)
  74203. | ((val >> 24) & 0xFF);
  74204. };
  74205. /**
  74206. * It is assumed that the texture has already been created & is currently bound
  74207. */
  74208. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  74209. switch (this.loadType) {
  74210. case KhronosTextureContainer.COMPRESSED_2D:
  74211. this._upload2DCompressedLevels(gl, loadMipmaps);
  74212. break;
  74213. case KhronosTextureContainer.TEX_2D:
  74214. case KhronosTextureContainer.COMPRESSED_3D:
  74215. case KhronosTextureContainer.TEX_3D:
  74216. }
  74217. };
  74218. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  74219. // initialize width & height for level 1
  74220. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  74221. var width = this.pixelWidth;
  74222. var height = this.pixelHeight;
  74223. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  74224. for (var level = 0; level < mipmapCount; level++) {
  74225. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  74226. for (var face = 0; face < this.numberOfFaces; face++) {
  74227. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  74228. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  74229. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  74230. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  74231. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  74232. }
  74233. width = Math.max(1.0, width * 0.5);
  74234. height = Math.max(1.0, height * 0.5);
  74235. }
  74236. };
  74237. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  74238. // load types
  74239. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  74240. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  74241. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  74242. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  74243. return KhronosTextureContainer;
  74244. }());
  74245. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  74246. })(BABYLON || (BABYLON = {}));
  74247. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  74248. var BABYLON;
  74249. (function (BABYLON) {
  74250. var Debug = /** @class */ (function () {
  74251. function Debug() {
  74252. }
  74253. Debug.AxesViewer = /** @class */ (function () {
  74254. function AxesViewer(scene, scaleLines) {
  74255. if (scaleLines === void 0) { scaleLines = 1; }
  74256. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74257. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74258. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74259. this.scaleLines = 1;
  74260. this.scaleLines = scaleLines;
  74261. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  74262. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  74263. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  74264. this._xmesh.renderingGroupId = 2;
  74265. this._ymesh.renderingGroupId = 2;
  74266. this._zmesh.renderingGroupId = 2;
  74267. this._xmesh.material.checkReadyOnlyOnce = true;
  74268. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  74269. this._ymesh.material.checkReadyOnlyOnce = true;
  74270. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  74271. this._zmesh.material.checkReadyOnlyOnce = true;
  74272. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  74273. this.scene = scene;
  74274. }
  74275. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  74276. var scaleLines = this.scaleLines;
  74277. if (this._xmesh) {
  74278. this._xmesh.position.copyFrom(position);
  74279. }
  74280. if (this._ymesh) {
  74281. this._ymesh.position.copyFrom(position);
  74282. }
  74283. if (this._zmesh) {
  74284. this._zmesh.position.copyFrom(position);
  74285. }
  74286. var point2 = this._xline[1];
  74287. point2.x = xaxis.x * scaleLines;
  74288. point2.y = xaxis.y * scaleLines;
  74289. point2.z = xaxis.z * scaleLines;
  74290. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  74291. point2 = this._yline[1];
  74292. point2.x = yaxis.x * scaleLines;
  74293. point2.y = yaxis.y * scaleLines;
  74294. point2.z = yaxis.z * scaleLines;
  74295. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  74296. point2 = this._zline[1];
  74297. point2.x = zaxis.x * scaleLines;
  74298. point2.y = zaxis.y * scaleLines;
  74299. point2.z = zaxis.z * scaleLines;
  74300. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  74301. };
  74302. AxesViewer.prototype.dispose = function () {
  74303. if (this._xmesh) {
  74304. this._xmesh.dispose();
  74305. }
  74306. if (this._ymesh) {
  74307. this._ymesh.dispose();
  74308. }
  74309. if (this._zmesh) {
  74310. this._zmesh.dispose();
  74311. }
  74312. this._xmesh = null;
  74313. this._ymesh = null;
  74314. this._zmesh = null;
  74315. this.scene = null;
  74316. };
  74317. return AxesViewer;
  74318. }());
  74319. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  74320. __extends(BoneAxesViewer, _super);
  74321. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  74322. if (scaleLines === void 0) { scaleLines = 1; }
  74323. var _this = _super.call(this, scene, scaleLines) || this;
  74324. _this.pos = BABYLON.Vector3.Zero();
  74325. _this.xaxis = BABYLON.Vector3.Zero();
  74326. _this.yaxis = BABYLON.Vector3.Zero();
  74327. _this.zaxis = BABYLON.Vector3.Zero();
  74328. _this.mesh = mesh;
  74329. _this.bone = bone;
  74330. return _this;
  74331. }
  74332. BoneAxesViewer.prototype.update = function () {
  74333. if (!this.mesh || !this.bone) {
  74334. return;
  74335. }
  74336. var bone = this.bone;
  74337. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  74338. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  74339. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  74340. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  74341. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  74342. };
  74343. BoneAxesViewer.prototype.dispose = function () {
  74344. if (this.mesh) {
  74345. this.mesh = null;
  74346. this.bone = null;
  74347. _super.prototype.dispose.call(this);
  74348. }
  74349. };
  74350. return BoneAxesViewer;
  74351. }(Debug.AxesViewer));
  74352. Debug.PhysicsViewer = /** @class */ (function () {
  74353. function PhysicsViewer(scene) {
  74354. this._impostors = [];
  74355. this._meshes = [];
  74356. this._numMeshes = 0;
  74357. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74358. var physicEngine = this._scene.getPhysicsEngine();
  74359. if (physicEngine) {
  74360. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  74361. }
  74362. }
  74363. PhysicsViewer.prototype._updateDebugMeshes = function () {
  74364. var plugin = this._physicsEnginePlugin;
  74365. for (var i = 0; i < this._numMeshes; i++) {
  74366. var impostor = this._impostors[i];
  74367. if (!impostor) {
  74368. continue;
  74369. }
  74370. if (impostor.isDisposed) {
  74371. this.hideImpostor(this._impostors[i--]);
  74372. }
  74373. else {
  74374. var mesh = this._meshes[i];
  74375. if (mesh && plugin) {
  74376. plugin.syncMeshWithImpostor(mesh, impostor);
  74377. }
  74378. }
  74379. }
  74380. };
  74381. PhysicsViewer.prototype.showImpostor = function (impostor) {
  74382. if (!this._scene) {
  74383. return;
  74384. }
  74385. for (var i = 0; i < this._numMeshes; i++) {
  74386. if (this._impostors[i] == impostor) {
  74387. return;
  74388. }
  74389. }
  74390. var debugMesh = this._getDebugMesh(impostor, this._scene);
  74391. if (debugMesh) {
  74392. this._impostors[this._numMeshes] = impostor;
  74393. this._meshes[this._numMeshes] = debugMesh;
  74394. if (this._numMeshes === 0) {
  74395. this._renderFunction = this._updateDebugMeshes.bind(this);
  74396. this._scene.registerBeforeRender(this._renderFunction);
  74397. }
  74398. this._numMeshes++;
  74399. }
  74400. };
  74401. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  74402. if (!impostor || !this._scene) {
  74403. return;
  74404. }
  74405. var removed = false;
  74406. for (var i = 0; i < this._numMeshes; i++) {
  74407. if (this._impostors[i] == impostor) {
  74408. var mesh = this._meshes[i];
  74409. if (!mesh) {
  74410. continue;
  74411. }
  74412. this._scene.removeMesh(mesh);
  74413. mesh.dispose();
  74414. this._numMeshes--;
  74415. if (this._numMeshes > 0) {
  74416. this._meshes[i] = this._meshes[this._numMeshes];
  74417. this._impostors[i] = this._impostors[this._numMeshes];
  74418. this._meshes[this._numMeshes] = null;
  74419. this._impostors[this._numMeshes] = null;
  74420. }
  74421. else {
  74422. this._meshes[0] = null;
  74423. this._impostors[0] = null;
  74424. }
  74425. removed = true;
  74426. break;
  74427. }
  74428. }
  74429. if (removed && this._numMeshes === 0) {
  74430. this._scene.unregisterBeforeRender(this._renderFunction);
  74431. }
  74432. };
  74433. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  74434. if (!this._debugMaterial) {
  74435. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  74436. this._debugMaterial.wireframe = true;
  74437. }
  74438. return this._debugMaterial;
  74439. };
  74440. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  74441. if (!this._debugBoxMesh) {
  74442. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  74443. this._debugBoxMesh.renderingGroupId = 1;
  74444. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74445. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  74446. scene.removeMesh(this._debugBoxMesh);
  74447. }
  74448. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  74449. };
  74450. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  74451. if (!this._debugSphereMesh) {
  74452. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  74453. this._debugSphereMesh.renderingGroupId = 1;
  74454. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74455. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  74456. scene.removeMesh(this._debugSphereMesh);
  74457. }
  74458. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  74459. };
  74460. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  74461. var mesh = null;
  74462. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  74463. mesh = this._getDebugBoxMesh(scene);
  74464. impostor.getBoxSizeToRef(mesh.scaling);
  74465. }
  74466. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  74467. mesh = this._getDebugSphereMesh(scene);
  74468. var radius = impostor.getRadius();
  74469. mesh.scaling.x = radius * 2;
  74470. mesh.scaling.y = radius * 2;
  74471. mesh.scaling.z = radius * 2;
  74472. }
  74473. return mesh;
  74474. };
  74475. PhysicsViewer.prototype.dispose = function () {
  74476. for (var i = 0; i < this._numMeshes; i++) {
  74477. this.hideImpostor(this._impostors[i]);
  74478. }
  74479. if (this._debugBoxMesh) {
  74480. this._debugBoxMesh.dispose();
  74481. }
  74482. if (this._debugSphereMesh) {
  74483. this._debugSphereMesh.dispose();
  74484. }
  74485. if (this._debugMaterial) {
  74486. this._debugMaterial.dispose();
  74487. }
  74488. this._impostors.length = 0;
  74489. this._scene = null;
  74490. this._physicsEnginePlugin = null;
  74491. };
  74492. return PhysicsViewer;
  74493. }());
  74494. Debug.SkeletonViewer = /** @class */ (function () {
  74495. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  74496. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  74497. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  74498. this.skeleton = skeleton;
  74499. this.mesh = mesh;
  74500. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  74501. this.renderingGroupId = renderingGroupId;
  74502. this.color = BABYLON.Color3.White();
  74503. this._debugLines = new Array();
  74504. this._isEnabled = false;
  74505. this._scene = scene;
  74506. this.update();
  74507. this._renderFunction = this.update.bind(this);
  74508. }
  74509. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  74510. get: function () {
  74511. return this._isEnabled;
  74512. },
  74513. set: function (value) {
  74514. if (this._isEnabled === value) {
  74515. return;
  74516. }
  74517. this._isEnabled = value;
  74518. if (value) {
  74519. this._scene.registerBeforeRender(this._renderFunction);
  74520. }
  74521. else {
  74522. this._scene.unregisterBeforeRender(this._renderFunction);
  74523. }
  74524. },
  74525. enumerable: true,
  74526. configurable: true
  74527. });
  74528. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  74529. if (x === void 0) { x = 0; }
  74530. if (y === void 0) { y = 0; }
  74531. if (z === void 0) { z = 0; }
  74532. var tmat = BABYLON.Tmp.Matrix[0];
  74533. var parentBone = bone.getParent();
  74534. tmat.copyFrom(bone.getLocalMatrix());
  74535. if (x !== 0 || y !== 0 || z !== 0) {
  74536. var tmat2 = BABYLON.Tmp.Matrix[1];
  74537. BABYLON.Matrix.IdentityToRef(tmat2);
  74538. tmat2.m[12] = x;
  74539. tmat2.m[13] = y;
  74540. tmat2.m[14] = z;
  74541. tmat2.multiplyToRef(tmat, tmat);
  74542. }
  74543. if (parentBone) {
  74544. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  74545. }
  74546. tmat.multiplyToRef(meshMat, tmat);
  74547. position.x = tmat.m[12];
  74548. position.y = tmat.m[13];
  74549. position.z = tmat.m[14];
  74550. };
  74551. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  74552. var len = bones.length;
  74553. var meshPos = this.mesh.position;
  74554. for (var i = 0; i < len; i++) {
  74555. var bone = bones[i];
  74556. var points = this._debugLines[i];
  74557. if (!points) {
  74558. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74559. this._debugLines[i] = points;
  74560. }
  74561. this._getBonePosition(points[0], bone, meshMat);
  74562. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  74563. points[0].subtractInPlace(meshPos);
  74564. points[1].subtractInPlace(meshPos);
  74565. }
  74566. };
  74567. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  74568. var len = bones.length;
  74569. var boneNum = 0;
  74570. var meshPos = this.mesh.position;
  74571. for (var i = len - 1; i >= 0; i--) {
  74572. var childBone = bones[i];
  74573. var parentBone = childBone.getParent();
  74574. if (!parentBone) {
  74575. continue;
  74576. }
  74577. var points = this._debugLines[boneNum];
  74578. if (!points) {
  74579. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74580. this._debugLines[boneNum] = points;
  74581. }
  74582. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  74583. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  74584. points[0].subtractInPlace(meshPos);
  74585. points[1].subtractInPlace(meshPos);
  74586. boneNum++;
  74587. }
  74588. };
  74589. SkeletonViewer.prototype.update = function () {
  74590. if (this.autoUpdateBonesMatrices) {
  74591. this.skeleton.computeAbsoluteTransforms();
  74592. }
  74593. if (this.skeleton.bones[0].length === undefined) {
  74594. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74595. }
  74596. else {
  74597. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74598. }
  74599. if (!this._debugMesh) {
  74600. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  74601. this._debugMesh.renderingGroupId = this.renderingGroupId;
  74602. }
  74603. else {
  74604. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  74605. }
  74606. this._debugMesh.position.copyFrom(this.mesh.position);
  74607. this._debugMesh.color = this.color;
  74608. };
  74609. SkeletonViewer.prototype.dispose = function () {
  74610. if (this._debugMesh) {
  74611. this.isEnabled = false;
  74612. this._debugMesh.dispose();
  74613. this._debugMesh = null;
  74614. }
  74615. };
  74616. return SkeletonViewer;
  74617. }());
  74618. return Debug;
  74619. }());
  74620. BABYLON.Debug = Debug;
  74621. })(BABYLON || (BABYLON = {}));
  74622. //# sourceMappingURL=babylon.debugModules.js.map
  74623. var BABYLON;
  74624. (function (BABYLON) {
  74625. var RayHelper = /** @class */ (function () {
  74626. function RayHelper(ray) {
  74627. this.ray = ray;
  74628. }
  74629. RayHelper.CreateAndShow = function (ray, scene, color) {
  74630. var helper = new RayHelper(ray);
  74631. helper.show(scene, color);
  74632. return helper;
  74633. };
  74634. RayHelper.prototype.show = function (scene, color) {
  74635. if (!this._renderFunction && this.ray) {
  74636. var ray = this.ray;
  74637. this._renderFunction = this._render.bind(this);
  74638. this._scene = scene;
  74639. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  74640. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  74641. if (this._renderFunction) {
  74642. this._scene.registerBeforeRender(this._renderFunction);
  74643. }
  74644. }
  74645. if (color && this._renderLine) {
  74646. this._renderLine.color.copyFrom(color);
  74647. }
  74648. };
  74649. RayHelper.prototype.hide = function () {
  74650. if (this._renderFunction && this._scene) {
  74651. this._scene.unregisterBeforeRender(this._renderFunction);
  74652. this._scene = null;
  74653. this._renderFunction = null;
  74654. if (this._renderLine) {
  74655. this._renderLine.dispose();
  74656. this._renderLine = null;
  74657. }
  74658. this._renderPoints = [];
  74659. }
  74660. };
  74661. RayHelper.prototype._render = function () {
  74662. var ray = this.ray;
  74663. if (!ray) {
  74664. return;
  74665. }
  74666. var point = this._renderPoints[1];
  74667. var len = Math.min(ray.length, 1000000);
  74668. point.copyFrom(ray.direction);
  74669. point.scaleInPlace(len);
  74670. point.addInPlace(ray.origin);
  74671. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  74672. };
  74673. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  74674. this._attachedToMesh = mesh;
  74675. var ray = this.ray;
  74676. if (!ray) {
  74677. return;
  74678. }
  74679. if (!ray.direction) {
  74680. ray.direction = BABYLON.Vector3.Zero();
  74681. }
  74682. if (!ray.origin) {
  74683. ray.origin = BABYLON.Vector3.Zero();
  74684. }
  74685. if (length) {
  74686. ray.length = length;
  74687. }
  74688. if (!meshSpaceOrigin) {
  74689. meshSpaceOrigin = BABYLON.Vector3.Zero();
  74690. }
  74691. if (!meshSpaceDirection) {
  74692. // -1 so that this will work with Mesh.lookAt
  74693. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  74694. }
  74695. if (!this._meshSpaceDirection) {
  74696. this._meshSpaceDirection = meshSpaceDirection.clone();
  74697. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  74698. }
  74699. else {
  74700. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  74701. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  74702. }
  74703. if (!this._updateToMeshFunction) {
  74704. this._updateToMeshFunction = this._updateToMesh.bind(this);
  74705. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  74706. }
  74707. this._updateToMesh();
  74708. };
  74709. RayHelper.prototype.detachFromMesh = function () {
  74710. if (this._attachedToMesh) {
  74711. if (this._updateToMeshFunction) {
  74712. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  74713. }
  74714. this._attachedToMesh = null;
  74715. this._updateToMeshFunction = null;
  74716. }
  74717. };
  74718. RayHelper.prototype._updateToMesh = function () {
  74719. var ray = this.ray;
  74720. if (!this._attachedToMesh || !ray) {
  74721. return;
  74722. }
  74723. if (this._attachedToMesh._isDisposed) {
  74724. this.detachFromMesh();
  74725. return;
  74726. }
  74727. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  74728. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  74729. };
  74730. RayHelper.prototype.dispose = function () {
  74731. this.hide();
  74732. this.detachFromMesh();
  74733. this.ray = null;
  74734. };
  74735. return RayHelper;
  74736. }());
  74737. BABYLON.RayHelper = RayHelper;
  74738. })(BABYLON || (BABYLON = {}));
  74739. //# sourceMappingURL=babylon.rayHelper.js.map
  74740. var BABYLON;
  74741. (function (BABYLON) {
  74742. // load the inspector using require, if not present in the global namespace.
  74743. var DebugLayer = /** @class */ (function () {
  74744. function DebugLayer(scene) {
  74745. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74746. this._scene = scene;
  74747. // load inspector using require, if it doesn't exist on the global namespace.
  74748. }
  74749. /** Creates the inspector window. */
  74750. DebugLayer.prototype._createInspector = function (config) {
  74751. if (config === void 0) { config = {}; }
  74752. var popup = config.popup || false;
  74753. var initialTab = config.initialTab || 0;
  74754. var parentElement = config.parentElement || null;
  74755. if (!this._inspector) {
  74756. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74757. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  74758. } // else nothing to do,; instance is already existing
  74759. };
  74760. DebugLayer.prototype.isVisible = function () {
  74761. if (!this._inspector) {
  74762. return false;
  74763. }
  74764. return true;
  74765. };
  74766. DebugLayer.prototype.hide = function () {
  74767. if (this._inspector) {
  74768. try {
  74769. this._inspector.dispose();
  74770. }
  74771. catch (e) {
  74772. // If the inspector has been removed directly from the inspector tool
  74773. }
  74774. this._inspector = null;
  74775. }
  74776. };
  74777. DebugLayer.prototype.show = function (config) {
  74778. if (config === void 0) { config = {}; }
  74779. if (typeof this.BJSINSPECTOR == 'undefined') {
  74780. // Load inspector and add it to the DOM
  74781. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  74782. }
  74783. else {
  74784. // Otherwise creates the inspector
  74785. this._createInspector(config);
  74786. }
  74787. };
  74788. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  74789. return DebugLayer;
  74790. }());
  74791. BABYLON.DebugLayer = DebugLayer;
  74792. })(BABYLON || (BABYLON = {}));
  74793. //# sourceMappingURL=babylon.debugLayer.js.map
  74794. var BABYLON;
  74795. (function (BABYLON) {
  74796. var BoundingBoxRenderer = /** @class */ (function () {
  74797. function BoundingBoxRenderer(scene) {
  74798. this.frontColor = new BABYLON.Color3(1, 1, 1);
  74799. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  74800. this.showBackLines = true;
  74801. this.renderList = new BABYLON.SmartArray(32);
  74802. this._vertexBuffers = {};
  74803. this._scene = scene;
  74804. }
  74805. BoundingBoxRenderer.prototype._prepareRessources = function () {
  74806. if (this._colorShader) {
  74807. return;
  74808. }
  74809. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  74810. attributes: [BABYLON.VertexBuffer.PositionKind],
  74811. uniforms: ["world", "viewProjection", "color"]
  74812. });
  74813. var engine = this._scene.getEngine();
  74814. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  74815. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  74816. this._createIndexBuffer();
  74817. };
  74818. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  74819. var engine = this._scene.getEngine();
  74820. 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]);
  74821. };
  74822. BoundingBoxRenderer.prototype._rebuild = function () {
  74823. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74824. if (vb) {
  74825. vb._rebuild();
  74826. }
  74827. this._createIndexBuffer();
  74828. };
  74829. BoundingBoxRenderer.prototype.reset = function () {
  74830. this.renderList.reset();
  74831. };
  74832. BoundingBoxRenderer.prototype.render = function () {
  74833. if (this.renderList.length === 0) {
  74834. return;
  74835. }
  74836. this._prepareRessources();
  74837. if (!this._colorShader.isReady()) {
  74838. return;
  74839. }
  74840. var engine = this._scene.getEngine();
  74841. engine.setDepthWrite(false);
  74842. this._colorShader._preBind();
  74843. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  74844. var boundingBox = this.renderList.data[boundingBoxIndex];
  74845. var min = boundingBox.minimum;
  74846. var max = boundingBox.maximum;
  74847. var diff = max.subtract(min);
  74848. var median = min.add(diff.scale(0.5));
  74849. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74850. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74851. .multiply(boundingBox.getWorldMatrix());
  74852. // VBOs
  74853. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74854. if (this.showBackLines) {
  74855. // Back
  74856. engine.setDepthFunctionToGreaterOrEqual();
  74857. this._scene.resetCachedMaterial();
  74858. this._colorShader.setColor4("color", this.backColor.toColor4());
  74859. this._colorShader.bind(worldMatrix);
  74860. // Draw order
  74861. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74862. }
  74863. // Front
  74864. engine.setDepthFunctionToLess();
  74865. this._scene.resetCachedMaterial();
  74866. this._colorShader.setColor4("color", this.frontColor.toColor4());
  74867. this._colorShader.bind(worldMatrix);
  74868. // Draw order
  74869. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74870. }
  74871. this._colorShader.unbind();
  74872. engine.setDepthFunctionToLessOrEqual();
  74873. engine.setDepthWrite(true);
  74874. };
  74875. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  74876. this._prepareRessources();
  74877. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  74878. return;
  74879. }
  74880. var engine = this._scene.getEngine();
  74881. engine.setDepthWrite(false);
  74882. engine.setColorWrite(false);
  74883. this._colorShader._preBind();
  74884. var boundingBox = mesh._boundingInfo.boundingBox;
  74885. var min = boundingBox.minimum;
  74886. var max = boundingBox.maximum;
  74887. var diff = max.subtract(min);
  74888. var median = min.add(diff.scale(0.5));
  74889. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74890. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74891. .multiply(boundingBox.getWorldMatrix());
  74892. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74893. engine.setDepthFunctionToLess();
  74894. this._scene.resetCachedMaterial();
  74895. this._colorShader.bind(worldMatrix);
  74896. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74897. this._colorShader.unbind();
  74898. engine.setDepthFunctionToLessOrEqual();
  74899. engine.setDepthWrite(true);
  74900. engine.setColorWrite(true);
  74901. };
  74902. BoundingBoxRenderer.prototype.dispose = function () {
  74903. if (!this._colorShader) {
  74904. return;
  74905. }
  74906. this.renderList.dispose();
  74907. this._colorShader.dispose();
  74908. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74909. if (buffer) {
  74910. buffer.dispose();
  74911. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74912. }
  74913. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74914. };
  74915. return BoundingBoxRenderer;
  74916. }());
  74917. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  74918. })(BABYLON || (BABYLON = {}));
  74919. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  74920. var BABYLON;
  74921. (function (BABYLON) {
  74922. var MorphTarget = /** @class */ (function () {
  74923. function MorphTarget(name, influence) {
  74924. if (influence === void 0) { influence = 0; }
  74925. this.name = name;
  74926. this.animations = new Array();
  74927. this._positions = null;
  74928. this._normals = null;
  74929. this._tangents = null;
  74930. this.onInfluenceChanged = new BABYLON.Observable();
  74931. this.influence = influence;
  74932. }
  74933. Object.defineProperty(MorphTarget.prototype, "influence", {
  74934. get: function () {
  74935. return this._influence;
  74936. },
  74937. set: function (influence) {
  74938. if (this._influence === influence) {
  74939. return;
  74940. }
  74941. var previous = this._influence;
  74942. this._influence = influence;
  74943. if (this.onInfluenceChanged.hasObservers) {
  74944. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  74945. }
  74946. },
  74947. enumerable: true,
  74948. configurable: true
  74949. });
  74950. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  74951. get: function () {
  74952. return !!this._positions;
  74953. },
  74954. enumerable: true,
  74955. configurable: true
  74956. });
  74957. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  74958. get: function () {
  74959. return !!this._normals;
  74960. },
  74961. enumerable: true,
  74962. configurable: true
  74963. });
  74964. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  74965. get: function () {
  74966. return !!this._tangents;
  74967. },
  74968. enumerable: true,
  74969. configurable: true
  74970. });
  74971. MorphTarget.prototype.setPositions = function (data) {
  74972. this._positions = data;
  74973. };
  74974. MorphTarget.prototype.getPositions = function () {
  74975. return this._positions;
  74976. };
  74977. MorphTarget.prototype.setNormals = function (data) {
  74978. this._normals = data;
  74979. };
  74980. MorphTarget.prototype.getNormals = function () {
  74981. return this._normals;
  74982. };
  74983. MorphTarget.prototype.setTangents = function (data) {
  74984. this._tangents = data;
  74985. };
  74986. MorphTarget.prototype.getTangents = function () {
  74987. return this._tangents;
  74988. };
  74989. /**
  74990. * Serializes the current target into a Serialization object.
  74991. * Returns the serialized object.
  74992. */
  74993. MorphTarget.prototype.serialize = function () {
  74994. var serializationObject = {};
  74995. serializationObject.name = this.name;
  74996. serializationObject.influence = this.influence;
  74997. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  74998. if (this.hasNormals) {
  74999. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  75000. }
  75001. if (this.hasTangents) {
  75002. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  75003. }
  75004. // Animations
  75005. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  75006. return serializationObject;
  75007. };
  75008. // Statics
  75009. MorphTarget.Parse = function (serializationObject) {
  75010. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  75011. result.setPositions(serializationObject.positions);
  75012. if (serializationObject.normals) {
  75013. result.setNormals(serializationObject.normals);
  75014. }
  75015. if (serializationObject.tangents) {
  75016. result.setTangents(serializationObject.tangents);
  75017. }
  75018. // Animations
  75019. if (serializationObject.animations) {
  75020. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  75021. var parsedAnimation = serializationObject.animations[animationIndex];
  75022. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  75023. }
  75024. }
  75025. return result;
  75026. };
  75027. MorphTarget.FromMesh = function (mesh, name, influence) {
  75028. if (!name) {
  75029. name = mesh.name;
  75030. }
  75031. var result = new MorphTarget(name, influence);
  75032. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75033. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75034. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  75035. }
  75036. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  75037. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  75038. }
  75039. return result;
  75040. };
  75041. return MorphTarget;
  75042. }());
  75043. BABYLON.MorphTarget = MorphTarget;
  75044. })(BABYLON || (BABYLON = {}));
  75045. //# sourceMappingURL=babylon.morphTarget.js.map
  75046. var BABYLON;
  75047. (function (BABYLON) {
  75048. var MorphTargetManager = /** @class */ (function () {
  75049. function MorphTargetManager(scene) {
  75050. if (scene === void 0) { scene = null; }
  75051. this._targets = new Array();
  75052. this._targetObservable = new Array();
  75053. this._activeTargets = new BABYLON.SmartArray(16);
  75054. this._supportsNormals = false;
  75055. this._supportsTangents = false;
  75056. this._vertexCount = 0;
  75057. this._uniqueId = 0;
  75058. this._tempInfluences = new Array();
  75059. if (!scene) {
  75060. scene = BABYLON.Engine.LastCreatedScene;
  75061. }
  75062. this._scene = scene;
  75063. if (this._scene) {
  75064. this._scene.morphTargetManagers.push(this);
  75065. this._uniqueId = this._scene.getUniqueId();
  75066. }
  75067. }
  75068. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  75069. get: function () {
  75070. return this._uniqueId;
  75071. },
  75072. enumerable: true,
  75073. configurable: true
  75074. });
  75075. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  75076. get: function () {
  75077. return this._vertexCount;
  75078. },
  75079. enumerable: true,
  75080. configurable: true
  75081. });
  75082. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  75083. get: function () {
  75084. return this._supportsNormals;
  75085. },
  75086. enumerable: true,
  75087. configurable: true
  75088. });
  75089. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  75090. get: function () {
  75091. return this._supportsTangents;
  75092. },
  75093. enumerable: true,
  75094. configurable: true
  75095. });
  75096. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  75097. get: function () {
  75098. return this._targets.length;
  75099. },
  75100. enumerable: true,
  75101. configurable: true
  75102. });
  75103. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  75104. get: function () {
  75105. return this._activeTargets.length;
  75106. },
  75107. enumerable: true,
  75108. configurable: true
  75109. });
  75110. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  75111. get: function () {
  75112. return this._influences;
  75113. },
  75114. enumerable: true,
  75115. configurable: true
  75116. });
  75117. MorphTargetManager.prototype.getActiveTarget = function (index) {
  75118. return this._activeTargets.data[index];
  75119. };
  75120. MorphTargetManager.prototype.getTarget = function (index) {
  75121. return this._targets[index];
  75122. };
  75123. MorphTargetManager.prototype.addTarget = function (target) {
  75124. var _this = this;
  75125. this._targets.push(target);
  75126. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  75127. _this._syncActiveTargets(needUpdate);
  75128. }));
  75129. this._syncActiveTargets(true);
  75130. };
  75131. MorphTargetManager.prototype.removeTarget = function (target) {
  75132. var index = this._targets.indexOf(target);
  75133. if (index >= 0) {
  75134. this._targets.splice(index, 1);
  75135. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  75136. this._syncActiveTargets(true);
  75137. }
  75138. };
  75139. /**
  75140. * Serializes the current manager into a Serialization object.
  75141. * Returns the serialized object.
  75142. */
  75143. MorphTargetManager.prototype.serialize = function () {
  75144. var serializationObject = {};
  75145. serializationObject.id = this.uniqueId;
  75146. serializationObject.targets = [];
  75147. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75148. var target = _a[_i];
  75149. serializationObject.targets.push(target.serialize());
  75150. }
  75151. return serializationObject;
  75152. };
  75153. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  75154. var influenceCount = 0;
  75155. this._activeTargets.reset();
  75156. this._supportsNormals = true;
  75157. this._supportsTangents = true;
  75158. this._vertexCount = 0;
  75159. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75160. var target = _a[_i];
  75161. this._activeTargets.push(target);
  75162. this._tempInfluences[influenceCount++] = target.influence;
  75163. var positions = target.getPositions();
  75164. if (positions) {
  75165. this._supportsNormals = this._supportsNormals && target.hasNormals;
  75166. this._supportsTangents = this._supportsTangents && target.hasTangents;
  75167. var vertexCount = positions.length / 3;
  75168. if (this._vertexCount === 0) {
  75169. this._vertexCount = vertexCount;
  75170. }
  75171. else if (this._vertexCount !== vertexCount) {
  75172. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  75173. return;
  75174. }
  75175. }
  75176. }
  75177. if (!this._influences || this._influences.length !== influenceCount) {
  75178. this._influences = new Float32Array(influenceCount);
  75179. }
  75180. for (var index = 0; index < influenceCount; index++) {
  75181. this._influences[index] = this._tempInfluences[index];
  75182. }
  75183. if (needUpdate && this._scene) {
  75184. // Flag meshes as dirty to resync with the active targets
  75185. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  75186. var mesh = _c[_b];
  75187. if (mesh.morphTargetManager === this) {
  75188. mesh._syncGeometryWithMorphTargetManager();
  75189. }
  75190. }
  75191. }
  75192. };
  75193. // Statics
  75194. MorphTargetManager.Parse = function (serializationObject, scene) {
  75195. var result = new MorphTargetManager(scene);
  75196. result._uniqueId = serializationObject.id;
  75197. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  75198. var targetData = _a[_i];
  75199. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  75200. }
  75201. return result;
  75202. };
  75203. return MorphTargetManager;
  75204. }());
  75205. BABYLON.MorphTargetManager = MorphTargetManager;
  75206. })(BABYLON || (BABYLON = {}));
  75207. //# sourceMappingURL=babylon.morphTargetManager.js.map
  75208. var BABYLON;
  75209. (function (BABYLON) {
  75210. var Octree = /** @class */ (function () {
  75211. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  75212. if (maxDepth === void 0) { maxDepth = 2; }
  75213. this.maxDepth = maxDepth;
  75214. this.dynamicContent = new Array();
  75215. this._maxBlockCapacity = maxBlockCapacity || 64;
  75216. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  75217. this._creationFunc = creationFunc;
  75218. }
  75219. // Methods
  75220. Octree.prototype.update = function (worldMin, worldMax, entries) {
  75221. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  75222. };
  75223. Octree.prototype.addMesh = function (entry) {
  75224. for (var index = 0; index < this.blocks.length; index++) {
  75225. var block = this.blocks[index];
  75226. block.addEntry(entry);
  75227. }
  75228. };
  75229. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  75230. this._selectionContent.reset();
  75231. for (var index = 0; index < this.blocks.length; index++) {
  75232. var block = this.blocks[index];
  75233. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  75234. }
  75235. if (allowDuplicate) {
  75236. this._selectionContent.concat(this.dynamicContent);
  75237. }
  75238. else {
  75239. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75240. }
  75241. return this._selectionContent;
  75242. };
  75243. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  75244. this._selectionContent.reset();
  75245. for (var index = 0; index < this.blocks.length; index++) {
  75246. var block = this.blocks[index];
  75247. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  75248. }
  75249. if (allowDuplicate) {
  75250. this._selectionContent.concat(this.dynamicContent);
  75251. }
  75252. else {
  75253. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75254. }
  75255. return this._selectionContent;
  75256. };
  75257. Octree.prototype.intersectsRay = function (ray) {
  75258. this._selectionContent.reset();
  75259. for (var index = 0; index < this.blocks.length; index++) {
  75260. var block = this.blocks[index];
  75261. block.intersectsRay(ray, this._selectionContent);
  75262. }
  75263. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75264. return this._selectionContent;
  75265. };
  75266. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  75267. target.blocks = new Array();
  75268. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  75269. // Segmenting space
  75270. for (var x = 0; x < 2; x++) {
  75271. for (var y = 0; y < 2; y++) {
  75272. for (var z = 0; z < 2; z++) {
  75273. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  75274. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  75275. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  75276. block.addEntries(entries);
  75277. target.blocks.push(block);
  75278. }
  75279. }
  75280. }
  75281. };
  75282. Octree.CreationFuncForMeshes = function (entry, block) {
  75283. var boundingInfo = entry.getBoundingInfo();
  75284. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75285. block.entries.push(entry);
  75286. }
  75287. };
  75288. Octree.CreationFuncForSubMeshes = function (entry, block) {
  75289. var boundingInfo = entry.getBoundingInfo();
  75290. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75291. block.entries.push(entry);
  75292. }
  75293. };
  75294. return Octree;
  75295. }());
  75296. BABYLON.Octree = Octree;
  75297. })(BABYLON || (BABYLON = {}));
  75298. //# sourceMappingURL=babylon.octree.js.map
  75299. var BABYLON;
  75300. (function (BABYLON) {
  75301. var OctreeBlock = /** @class */ (function () {
  75302. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  75303. this.entries = new Array();
  75304. this._boundingVectors = new Array();
  75305. this._capacity = capacity;
  75306. this._depth = depth;
  75307. this._maxDepth = maxDepth;
  75308. this._creationFunc = creationFunc;
  75309. this._minPoint = minPoint;
  75310. this._maxPoint = maxPoint;
  75311. this._boundingVectors.push(minPoint.clone());
  75312. this._boundingVectors.push(maxPoint.clone());
  75313. this._boundingVectors.push(minPoint.clone());
  75314. this._boundingVectors[2].x = maxPoint.x;
  75315. this._boundingVectors.push(minPoint.clone());
  75316. this._boundingVectors[3].y = maxPoint.y;
  75317. this._boundingVectors.push(minPoint.clone());
  75318. this._boundingVectors[4].z = maxPoint.z;
  75319. this._boundingVectors.push(maxPoint.clone());
  75320. this._boundingVectors[5].z = minPoint.z;
  75321. this._boundingVectors.push(maxPoint.clone());
  75322. this._boundingVectors[6].x = minPoint.x;
  75323. this._boundingVectors.push(maxPoint.clone());
  75324. this._boundingVectors[7].y = minPoint.y;
  75325. }
  75326. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  75327. // Property
  75328. get: function () {
  75329. return this._capacity;
  75330. },
  75331. enumerable: true,
  75332. configurable: true
  75333. });
  75334. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  75335. get: function () {
  75336. return this._minPoint;
  75337. },
  75338. enumerable: true,
  75339. configurable: true
  75340. });
  75341. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  75342. get: function () {
  75343. return this._maxPoint;
  75344. },
  75345. enumerable: true,
  75346. configurable: true
  75347. });
  75348. // Methods
  75349. OctreeBlock.prototype.addEntry = function (entry) {
  75350. if (this.blocks) {
  75351. for (var index = 0; index < this.blocks.length; index++) {
  75352. var block = this.blocks[index];
  75353. block.addEntry(entry);
  75354. }
  75355. return;
  75356. }
  75357. this._creationFunc(entry, this);
  75358. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  75359. this.createInnerBlocks();
  75360. }
  75361. };
  75362. OctreeBlock.prototype.addEntries = function (entries) {
  75363. for (var index = 0; index < entries.length; index++) {
  75364. var mesh = entries[index];
  75365. this.addEntry(mesh);
  75366. }
  75367. };
  75368. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  75369. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  75370. if (this.blocks) {
  75371. for (var index = 0; index < this.blocks.length; index++) {
  75372. var block = this.blocks[index];
  75373. block.select(frustumPlanes, selection, allowDuplicate);
  75374. }
  75375. return;
  75376. }
  75377. if (allowDuplicate) {
  75378. selection.concat(this.entries);
  75379. }
  75380. else {
  75381. selection.concatWithNoDuplicate(this.entries);
  75382. }
  75383. }
  75384. };
  75385. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  75386. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  75387. if (this.blocks) {
  75388. for (var index = 0; index < this.blocks.length; index++) {
  75389. var block = this.blocks[index];
  75390. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  75391. }
  75392. return;
  75393. }
  75394. if (allowDuplicate) {
  75395. selection.concat(this.entries);
  75396. }
  75397. else {
  75398. selection.concatWithNoDuplicate(this.entries);
  75399. }
  75400. }
  75401. };
  75402. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  75403. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  75404. if (this.blocks) {
  75405. for (var index = 0; index < this.blocks.length; index++) {
  75406. var block = this.blocks[index];
  75407. block.intersectsRay(ray, selection);
  75408. }
  75409. return;
  75410. }
  75411. selection.concatWithNoDuplicate(this.entries);
  75412. }
  75413. };
  75414. OctreeBlock.prototype.createInnerBlocks = function () {
  75415. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  75416. };
  75417. return OctreeBlock;
  75418. }());
  75419. BABYLON.OctreeBlock = OctreeBlock;
  75420. })(BABYLON || (BABYLON = {}));
  75421. //# sourceMappingURL=babylon.octreeBlock.js.map
  75422. var BABYLON;
  75423. (function (BABYLON) {
  75424. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  75425. __extends(VRDistortionCorrectionPostProcess, _super);
  75426. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  75427. var _this = _super.call(this, name, "vrDistortionCorrection", [
  75428. 'LensCenter',
  75429. 'Scale',
  75430. 'ScaleIn',
  75431. 'HmdWarpParam'
  75432. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  75433. _this._isRightEye = isRightEye;
  75434. _this._distortionFactors = vrMetrics.distortionK;
  75435. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  75436. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  75437. _this.adaptScaleToCurrentViewport = true;
  75438. _this.onSizeChangedObservable.add(function () {
  75439. _this.aspectRatio = _this.width * .5 / _this.height;
  75440. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  75441. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  75442. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  75443. });
  75444. _this.onApplyObservable.add(function (effect) {
  75445. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  75446. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  75447. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  75448. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  75449. });
  75450. return _this;
  75451. }
  75452. return VRDistortionCorrectionPostProcess;
  75453. }(BABYLON.PostProcess));
  75454. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  75455. })(BABYLON || (BABYLON = {}));
  75456. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  75457. var BABYLON;
  75458. (function (BABYLON) {
  75459. var AnaglyphPostProcess = /** @class */ (function (_super) {
  75460. __extends(AnaglyphPostProcess, _super);
  75461. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  75462. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  75463. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75464. _this.onApplyObservable.add(function (effect) {
  75465. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  75466. });
  75467. return _this;
  75468. }
  75469. return AnaglyphPostProcess;
  75470. }(BABYLON.PostProcess));
  75471. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  75472. })(BABYLON || (BABYLON = {}));
  75473. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  75474. var BABYLON;
  75475. (function (BABYLON) {
  75476. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  75477. __extends(StereoscopicInterlacePostProcess, _super);
  75478. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  75479. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  75480. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75481. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75482. _this.onSizeChangedObservable.add(function () {
  75483. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75484. });
  75485. _this.onApplyObservable.add(function (effect) {
  75486. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  75487. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  75488. });
  75489. return _this;
  75490. }
  75491. return StereoscopicInterlacePostProcess;
  75492. }(BABYLON.PostProcess));
  75493. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  75494. })(BABYLON || (BABYLON = {}));
  75495. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  75496. var BABYLON;
  75497. (function (BABYLON) {
  75498. /**
  75499. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  75500. * Screen rotation is taken into account.
  75501. */
  75502. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  75503. function FreeCameraDeviceOrientationInput() {
  75504. var _this = this;
  75505. this._screenOrientationAngle = 0;
  75506. this._screenQuaternion = new BABYLON.Quaternion();
  75507. this._alpha = 0;
  75508. this._beta = 0;
  75509. this._gamma = 0;
  75510. this._orientationChanged = function () {
  75511. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  75512. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  75513. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  75514. };
  75515. this._deviceOrientation = function (evt) {
  75516. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  75517. _this._beta = evt.beta !== null ? evt.beta : 0;
  75518. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  75519. };
  75520. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  75521. this._orientationChanged();
  75522. }
  75523. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  75524. get: function () {
  75525. return this._camera;
  75526. },
  75527. set: function (camera) {
  75528. this._camera = camera;
  75529. if (this._camera != null && !this._camera.rotationQuaternion) {
  75530. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  75531. }
  75532. },
  75533. enumerable: true,
  75534. configurable: true
  75535. });
  75536. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75537. window.addEventListener("orientationchange", this._orientationChanged);
  75538. window.addEventListener("deviceorientation", this._deviceOrientation);
  75539. //In certain cases, the attach control is called AFTER orientation was changed,
  75540. //So this is needed.
  75541. this._orientationChanged();
  75542. };
  75543. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  75544. window.removeEventListener("orientationchange", this._orientationChanged);
  75545. window.removeEventListener("deviceorientation", this._deviceOrientation);
  75546. };
  75547. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  75548. //if no device orientation provided, don't update the rotation.
  75549. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  75550. if (!this._alpha)
  75551. return;
  75552. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  75553. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  75554. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  75555. //Mirror on XY Plane
  75556. this._camera.rotationQuaternion.z *= -1;
  75557. this._camera.rotationQuaternion.w *= -1;
  75558. };
  75559. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  75560. return "FreeCameraDeviceOrientationInput";
  75561. };
  75562. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  75563. return "deviceOrientation";
  75564. };
  75565. return FreeCameraDeviceOrientationInput;
  75566. }());
  75567. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  75568. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  75569. })(BABYLON || (BABYLON = {}));
  75570. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  75571. var BABYLON;
  75572. (function (BABYLON) {
  75573. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  75574. function ArcRotateCameraVRDeviceOrientationInput() {
  75575. this.alphaCorrection = 1;
  75576. this.betaCorrection = 1;
  75577. this.gammaCorrection = 1;
  75578. this._alpha = 0;
  75579. this._gamma = 0;
  75580. this._dirty = false;
  75581. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  75582. }
  75583. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75584. this.camera.attachControl(element, noPreventDefault);
  75585. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  75586. };
  75587. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  75588. if (evt.alpha !== null) {
  75589. this._alpha = +evt.alpha | 0;
  75590. }
  75591. if (evt.gamma !== null) {
  75592. this._gamma = +evt.gamma | 0;
  75593. }
  75594. this._dirty = true;
  75595. };
  75596. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  75597. if (this._dirty) {
  75598. this._dirty = false;
  75599. if (this._gamma < 0) {
  75600. this._gamma = 180 + this._gamma;
  75601. }
  75602. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  75603. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  75604. }
  75605. };
  75606. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  75607. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  75608. };
  75609. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  75610. return "ArcRotateCameraVRDeviceOrientationInput";
  75611. };
  75612. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  75613. return "VRDeviceOrientation";
  75614. };
  75615. return ArcRotateCameraVRDeviceOrientationInput;
  75616. }());
  75617. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  75618. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  75619. })(BABYLON || (BABYLON = {}));
  75620. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  75621. var BABYLON;
  75622. (function (BABYLON) {
  75623. var VRCameraMetrics = /** @class */ (function () {
  75624. function VRCameraMetrics() {
  75625. this.compensateDistortion = true;
  75626. }
  75627. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  75628. get: function () {
  75629. return this.hResolution / (2 * this.vResolution);
  75630. },
  75631. enumerable: true,
  75632. configurable: true
  75633. });
  75634. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  75635. get: function () {
  75636. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  75637. },
  75638. enumerable: true,
  75639. configurable: true
  75640. });
  75641. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  75642. get: function () {
  75643. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75644. var h = (4 * meters) / this.hScreenSize;
  75645. return BABYLON.Matrix.Translation(h, 0, 0);
  75646. },
  75647. enumerable: true,
  75648. configurable: true
  75649. });
  75650. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  75651. get: function () {
  75652. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75653. var h = (4 * meters) / this.hScreenSize;
  75654. return BABYLON.Matrix.Translation(-h, 0, 0);
  75655. },
  75656. enumerable: true,
  75657. configurable: true
  75658. });
  75659. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  75660. get: function () {
  75661. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  75662. },
  75663. enumerable: true,
  75664. configurable: true
  75665. });
  75666. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  75667. get: function () {
  75668. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  75669. },
  75670. enumerable: true,
  75671. configurable: true
  75672. });
  75673. VRCameraMetrics.GetDefault = function () {
  75674. var result = new VRCameraMetrics();
  75675. result.hResolution = 1280;
  75676. result.vResolution = 800;
  75677. result.hScreenSize = 0.149759993;
  75678. result.vScreenSize = 0.0935999975;
  75679. result.vScreenCenter = 0.0467999987;
  75680. result.eyeToScreenDistance = 0.0410000011;
  75681. result.lensSeparationDistance = 0.0635000020;
  75682. result.interpupillaryDistance = 0.0640000030;
  75683. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  75684. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  75685. result.postProcessScaleFactor = 1.714605507808412;
  75686. result.lensCenterOffset = 0.151976421;
  75687. return result;
  75688. };
  75689. return VRCameraMetrics;
  75690. }());
  75691. BABYLON.VRCameraMetrics = VRCameraMetrics;
  75692. })(BABYLON || (BABYLON = {}));
  75693. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  75694. var BABYLON;
  75695. (function (BABYLON) {
  75696. /**
  75697. * This represents a WebVR camera.
  75698. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  75699. * @example http://doc.babylonjs.com/how_to/webvr_camera
  75700. */
  75701. var WebVRFreeCamera = /** @class */ (function (_super) {
  75702. __extends(WebVRFreeCamera, _super);
  75703. /**
  75704. * Instantiates a WebVRFreeCamera.
  75705. * @param name The name of the WebVRFreeCamera
  75706. * @param position The starting anchor position for the camera
  75707. * @param scene The scene the camera belongs to
  75708. * @param webVROptions a set of customizable options for the webVRCamera
  75709. */
  75710. function WebVRFreeCamera(name, position, scene, webVROptions) {
  75711. if (webVROptions === void 0) { webVROptions = {}; }
  75712. var _this = _super.call(this, name, position, scene) || this;
  75713. _this.webVROptions = webVROptions;
  75714. /**
  75715. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  75716. */
  75717. _this._vrDevice = null;
  75718. /**
  75719. * The rawPose of the vrDevice.
  75720. */
  75721. _this.rawPose = null;
  75722. _this._specsVersion = "1.1";
  75723. _this._attached = false;
  75724. _this._descendants = [];
  75725. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75726. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75727. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  75728. _this._standingMatrix = null;
  75729. /**
  75730. * Represents device position in babylon space.
  75731. */
  75732. _this.devicePosition = BABYLON.Vector3.Zero();
  75733. /**
  75734. * Represents device rotation in babylon space.
  75735. */
  75736. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  75737. /**
  75738. * The scale of the device to be used when translating from device space to babylon space.
  75739. */
  75740. _this.deviceScaleFactor = 1;
  75741. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75742. _this._worldToDevice = BABYLON.Matrix.Identity();
  75743. /**
  75744. * References to the webVR controllers for the vrDevice.
  75745. */
  75746. _this.controllers = [];
  75747. /**
  75748. * Emits an event when a controller is attached.
  75749. */
  75750. _this.onControllersAttachedObservable = new BABYLON.Observable();
  75751. /**
  75752. * Emits an event when a controller's mesh has been loaded;
  75753. */
  75754. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75755. /**
  75756. * If the rig cameras be used as parent instead of this camera.
  75757. */
  75758. _this.rigParenting = true;
  75759. _this._defaultHeight = undefined;
  75760. _this._workingVector = BABYLON.Vector3.Zero();
  75761. _this._oneVector = BABYLON.Vector3.One();
  75762. _this._workingMatrix = BABYLON.Matrix.Identity();
  75763. _this._cache.position = BABYLON.Vector3.Zero();
  75764. if (webVROptions.defaultHeight) {
  75765. _this._defaultHeight = webVROptions.defaultHeight;
  75766. _this.position.y = _this._defaultHeight;
  75767. }
  75768. _this.minZ = 0.1;
  75769. //legacy support - the compensation boolean was removed.
  75770. if (arguments.length === 5) {
  75771. _this.webVROptions = arguments[4];
  75772. }
  75773. // default webVR options
  75774. if (_this.webVROptions.trackPosition == undefined) {
  75775. _this.webVROptions.trackPosition = true;
  75776. }
  75777. if (_this.webVROptions.controllerMeshes == undefined) {
  75778. _this.webVROptions.controllerMeshes = true;
  75779. }
  75780. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  75781. _this.webVROptions.defaultLightingOnControllers = true;
  75782. }
  75783. _this.rotationQuaternion = new BABYLON.Quaternion();
  75784. if (_this.webVROptions && _this.webVROptions.positionScale) {
  75785. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  75786. }
  75787. //enable VR
  75788. var engine = _this.getEngine();
  75789. _this._onVREnabled = function (success) { if (success) {
  75790. _this.initControllers();
  75791. } };
  75792. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  75793. engine.initWebVR().add(function (event) {
  75794. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  75795. return;
  75796. }
  75797. _this._vrDevice = event.vrDisplay;
  75798. //reset the rig parameters.
  75799. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  75800. if (_this._attached) {
  75801. _this.getEngine().enableVR();
  75802. }
  75803. });
  75804. if (typeof (VRFrameData) !== "undefined")
  75805. _this._frameData = new VRFrameData();
  75806. /**
  75807. * The idea behind the following lines:
  75808. * objects that have the camera as parent should actually have the rig cameras as a parent.
  75809. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  75810. * the second will not show it correctly.
  75811. *
  75812. * To solve this - each object that has the camera as parent will be added to a protected array.
  75813. * When the rig camera renders, it will take this array and set all of those to be its children.
  75814. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  75815. * Amazing!
  75816. */
  75817. scene.onBeforeCameraRenderObservable.add(function (camera) {
  75818. if (camera.parent === _this && _this.rigParenting) {
  75819. _this._descendants = _this.getDescendants(true, function (n) {
  75820. // don't take the cameras or the controllers!
  75821. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  75822. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  75823. return !isController && !isRigCamera;
  75824. });
  75825. _this._descendants.forEach(function (node) {
  75826. node.parent = camera;
  75827. });
  75828. }
  75829. });
  75830. scene.onAfterCameraRenderObservable.add(function (camera) {
  75831. if (camera.parent === _this && _this.rigParenting) {
  75832. _this._descendants.forEach(function (node) {
  75833. node.parent = _this;
  75834. });
  75835. }
  75836. });
  75837. return _this;
  75838. }
  75839. /**
  75840. * Gets the device distance from the ground.
  75841. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  75842. */
  75843. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  75844. if (this._standingMatrix && this._defaultHeight === undefined) {
  75845. // Add standing matrix offset to get real offset from ground in room
  75846. this._standingMatrix.getTranslationToRef(this._workingVector);
  75847. return this._deviceRoomPosition.y + this._workingVector.y;
  75848. }
  75849. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  75850. return this._defaultHeight || 0;
  75851. };
  75852. /**
  75853. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  75854. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  75855. */
  75856. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  75857. var _this = this;
  75858. if (callback === void 0) { callback = function (bool) { }; }
  75859. // Use standing matrix if available
  75860. if (!navigator || !navigator.getVRDisplays) {
  75861. callback(false);
  75862. }
  75863. else {
  75864. navigator.getVRDisplays().then(function (displays) {
  75865. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  75866. callback(false);
  75867. }
  75868. else {
  75869. _this._standingMatrix = new BABYLON.Matrix();
  75870. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  75871. if (!_this.getScene().useRightHandedSystem) {
  75872. [2, 6, 8, 9, 14].forEach(function (num) {
  75873. if (_this._standingMatrix) {
  75874. _this._standingMatrix.m[num] *= -1;
  75875. }
  75876. });
  75877. }
  75878. callback(true);
  75879. }
  75880. });
  75881. }
  75882. };
  75883. /**
  75884. * Disposes the camera
  75885. */
  75886. WebVRFreeCamera.prototype.dispose = function () {
  75887. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  75888. _super.prototype.dispose.call(this);
  75889. };
  75890. /**
  75891. * Gets a vrController by name.
  75892. * @param name The name of the controller to retreive
  75893. * @returns the controller matching the name specified or null if not found
  75894. */
  75895. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  75896. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  75897. var gp = _a[_i];
  75898. if (gp.hand === name) {
  75899. return gp;
  75900. }
  75901. }
  75902. return null;
  75903. };
  75904. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  75905. /**
  75906. * The controller corrisponding to the users left hand.
  75907. */
  75908. get: function () {
  75909. if (!this._leftController) {
  75910. this._leftController = this.getControllerByName("left");
  75911. }
  75912. return this._leftController;
  75913. },
  75914. enumerable: true,
  75915. configurable: true
  75916. });
  75917. ;
  75918. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  75919. /**
  75920. * The controller corrisponding to the users right hand.
  75921. */
  75922. get: function () {
  75923. if (!this._rightController) {
  75924. this._rightController = this.getControllerByName("right");
  75925. }
  75926. return this._rightController;
  75927. },
  75928. enumerable: true,
  75929. configurable: true
  75930. });
  75931. ;
  75932. /**
  75933. * Casts a ray forward from the vrCamera's gaze.
  75934. * @param length Length of the ray (default: 100)
  75935. * @returns the ray corrisponding to the gaze
  75936. */
  75937. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  75938. if (length === void 0) { length = 100; }
  75939. if (this.leftCamera) {
  75940. // Use left eye to avoid computation to compute center on every call
  75941. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  75942. }
  75943. else {
  75944. return _super.prototype.getForwardRay.call(this, length);
  75945. }
  75946. };
  75947. /**
  75948. * Updates the camera based on device's frame data
  75949. */
  75950. WebVRFreeCamera.prototype._checkInputs = function () {
  75951. if (this._vrDevice && this._vrDevice.isPresenting) {
  75952. this._vrDevice.getFrameData(this._frameData);
  75953. this.updateFromDevice(this._frameData.pose);
  75954. }
  75955. _super.prototype._checkInputs.call(this);
  75956. };
  75957. /**
  75958. * Updates the poseControlled values based on the input device pose.
  75959. * @param poseData Pose coming from the device
  75960. */
  75961. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  75962. if (poseData && poseData.orientation) {
  75963. this.rawPose = poseData;
  75964. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  75965. if (this.getScene().useRightHandedSystem) {
  75966. this._deviceRoomRotationQuaternion.z *= -1;
  75967. this._deviceRoomRotationQuaternion.w *= -1;
  75968. }
  75969. if (this.webVROptions.trackPosition && this.rawPose.position) {
  75970. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  75971. if (this.getScene().useRightHandedSystem) {
  75972. this._deviceRoomPosition.z *= -1;
  75973. }
  75974. }
  75975. }
  75976. };
  75977. /**
  75978. * WebVR's attach control will start broadcasting frames to the device.
  75979. * Note that in certain browsers (chrome for example) this function must be called
  75980. * within a user-interaction callback. Example:
  75981. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  75982. *
  75983. * @param element html element to attach the vrDevice to
  75984. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  75985. */
  75986. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  75987. _super.prototype.attachControl.call(this, element, noPreventDefault);
  75988. this._attached = true;
  75989. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  75990. if (this._vrDevice) {
  75991. this.getEngine().enableVR();
  75992. }
  75993. };
  75994. /**
  75995. * Detaches the camera from the html element and disables VR
  75996. *
  75997. * @param element html element to detach from
  75998. */
  75999. WebVRFreeCamera.prototype.detachControl = function (element) {
  76000. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76001. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76002. _super.prototype.detachControl.call(this, element);
  76003. this._attached = false;
  76004. this.getEngine().disableVR();
  76005. };
  76006. /**
  76007. * @returns the name of this class
  76008. */
  76009. WebVRFreeCamera.prototype.getClassName = function () {
  76010. return "WebVRFreeCamera";
  76011. };
  76012. /**
  76013. * Calls resetPose on the vrDisplay
  76014. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  76015. */
  76016. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  76017. //uses the vrDisplay's "resetPose()".
  76018. //pitch and roll won't be affected.
  76019. this._vrDevice.resetPose();
  76020. };
  76021. /**
  76022. * Updates the rig cameras (left and right eye)
  76023. */
  76024. WebVRFreeCamera.prototype._updateRigCameras = function () {
  76025. var camLeft = this._rigCameras[0];
  76026. var camRight = this._rigCameras[1];
  76027. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76028. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76029. camLeft.position.copyFrom(this._deviceRoomPosition);
  76030. camRight.position.copyFrom(this._deviceRoomPosition);
  76031. };
  76032. /**
  76033. * Updates the cached values of the camera
  76034. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  76035. */
  76036. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  76037. var _this = this;
  76038. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  76039. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  76040. if (!this.updateCacheCalled) {
  76041. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  76042. this.updateCacheCalled = true;
  76043. this.update();
  76044. }
  76045. // Set working vector to the device position in room space rotated by the new rotation
  76046. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  76047. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  76048. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  76049. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  76050. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  76051. // Add translation from anchor position
  76052. this._deviceToWorld.getTranslationToRef(this._workingVector);
  76053. this._workingVector.addInPlace(this.position);
  76054. this._workingVector.subtractInPlace(this._cache.position);
  76055. this._deviceToWorld.setTranslation(this._workingVector);
  76056. // Set an inverted matrix to be used when updating the camera
  76057. this._deviceToWorld.invertToRef(this._worldToDevice);
  76058. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  76059. this.controllers.forEach(function (controller) {
  76060. controller._deviceToWorld = _this._deviceToWorld;
  76061. controller.update();
  76062. });
  76063. }
  76064. if (!ignoreParentClass) {
  76065. _super.prototype._updateCache.call(this);
  76066. }
  76067. this.updateCacheCalled = false;
  76068. };
  76069. /**
  76070. * Updates the current device position and rotation in the babylon world
  76071. */
  76072. WebVRFreeCamera.prototype.update = function () {
  76073. // Get current device position in babylon world
  76074. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  76075. // Get current device rotation in babylon world
  76076. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  76077. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  76078. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  76079. _super.prototype.update.call(this);
  76080. };
  76081. /**
  76082. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  76083. * @returns an identity matrix
  76084. */
  76085. WebVRFreeCamera.prototype._getViewMatrix = function () {
  76086. return BABYLON.Matrix.Identity();
  76087. };
  76088. /**
  76089. * This function is called by the two RIG cameras.
  76090. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  76091. */
  76092. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  76093. var _this = this;
  76094. //WebVR 1.1
  76095. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  76096. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  76097. if (!this.getScene().useRightHandedSystem) {
  76098. [2, 6, 8, 9, 14].forEach(function (num) {
  76099. _this._webvrViewMatrix.m[num] *= -1;
  76100. });
  76101. }
  76102. // update the camera rotation matrix
  76103. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  76104. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  76105. // Computing target and final matrix
  76106. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  76107. var parentCamera = this._cameraRigParams["parentCamera"];
  76108. // should the view matrix be updated with scale and position offset?
  76109. if (parentCamera.deviceScaleFactor !== 1) {
  76110. this._webvrViewMatrix.invert();
  76111. // scale the position, if set
  76112. if (parentCamera.deviceScaleFactor) {
  76113. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  76114. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  76115. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  76116. }
  76117. this._webvrViewMatrix.invert();
  76118. }
  76119. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  76120. return this._webvrViewMatrix;
  76121. };
  76122. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  76123. var _this = this;
  76124. var parentCamera = this.parent;
  76125. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  76126. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  76127. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  76128. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  76129. //babylon compatible matrix
  76130. if (!this.getScene().useRightHandedSystem) {
  76131. [8, 9, 10, 11].forEach(function (num) {
  76132. _this._projectionMatrix.m[num] *= -1;
  76133. });
  76134. }
  76135. return this._projectionMatrix;
  76136. };
  76137. /**
  76138. * Initializes the controllers and their meshes
  76139. */
  76140. WebVRFreeCamera.prototype.initControllers = function () {
  76141. var _this = this;
  76142. this.controllers = [];
  76143. var manager = this.getScene().gamepadManager;
  76144. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76145. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76146. var webVrController = gamepad;
  76147. if (webVrController.defaultModel) {
  76148. webVrController.defaultModel.setEnabled(false);
  76149. }
  76150. if (webVrController.hand === "right") {
  76151. _this._rightController = null;
  76152. }
  76153. if (webVrController.hand === "left") {
  76154. _this._rightController = null;
  76155. }
  76156. var controllerIndex = _this.controllers.indexOf(webVrController);
  76157. if (controllerIndex !== -1) {
  76158. _this.controllers.splice(controllerIndex, 1);
  76159. }
  76160. }
  76161. });
  76162. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76163. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76164. var webVrController_1 = gamepad;
  76165. webVrController_1._deviceToWorld = _this._deviceToWorld;
  76166. if (_this.webVROptions.controllerMeshes) {
  76167. if (webVrController_1.defaultModel) {
  76168. webVrController_1.defaultModel.setEnabled(true);
  76169. }
  76170. else {
  76171. // Load the meshes
  76172. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  76173. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  76174. if (_this.webVROptions.defaultLightingOnControllers) {
  76175. if (!_this._lightOnControllers) {
  76176. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  76177. }
  76178. var activateLightOnSubMeshes_1 = function (mesh, light) {
  76179. var children = mesh.getChildren();
  76180. if (children.length !== 0) {
  76181. children.forEach(function (mesh) {
  76182. light.includedOnlyMeshes.push(mesh);
  76183. activateLightOnSubMeshes_1(mesh, light);
  76184. });
  76185. }
  76186. };
  76187. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  76188. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  76189. }
  76190. });
  76191. }
  76192. }
  76193. webVrController_1.attachToPoseControlledCamera(_this);
  76194. // since this is async - sanity check. Is the controller already stored?
  76195. if (_this.controllers.indexOf(webVrController_1) === -1) {
  76196. //add to the controllers array
  76197. _this.controllers.push(webVrController_1);
  76198. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  76199. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  76200. // So we're overriding setting left & right manually to be sure
  76201. var firstViveWandDetected = false;
  76202. for (var i = 0; i < _this.controllers.length; i++) {
  76203. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76204. if (!firstViveWandDetected) {
  76205. firstViveWandDetected = true;
  76206. _this.controllers[i].hand = "left";
  76207. }
  76208. else {
  76209. _this.controllers[i].hand = "right";
  76210. }
  76211. }
  76212. }
  76213. //did we find enough controllers? Great! let the developer know.
  76214. if (_this.controllers.length >= 2) {
  76215. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  76216. }
  76217. }
  76218. }
  76219. });
  76220. };
  76221. return WebVRFreeCamera;
  76222. }(BABYLON.FreeCamera));
  76223. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  76224. })(BABYLON || (BABYLON = {}));
  76225. //# sourceMappingURL=babylon.webVRCamera.js.map
  76226. var BABYLON;
  76227. (function (BABYLON) {
  76228. // We're mainly based on the logic defined into the FreeCamera code
  76229. /**
  76230. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  76231. * being tilted forward or back and left or right.
  76232. */
  76233. var DeviceOrientationCamera = /** @class */ (function (_super) {
  76234. __extends(DeviceOrientationCamera, _super);
  76235. /**
  76236. * Creates a new device orientation camera. @see DeviceOrientationCamera
  76237. * @param name The name of the camera
  76238. * @param position The start position camera
  76239. * @param scene The scene the camera belongs to
  76240. */
  76241. function DeviceOrientationCamera(name, position, scene) {
  76242. var _this = _super.call(this, name, position, scene) || this;
  76243. _this._quaternionCache = new BABYLON.Quaternion();
  76244. _this.inputs.addDeviceOrientation();
  76245. return _this;
  76246. }
  76247. /**
  76248. * Gets the current instance class name ("DeviceOrientationCamera").
  76249. * This helps avoiding instanceof at run time.
  76250. * @returns the class name
  76251. */
  76252. DeviceOrientationCamera.prototype.getClassName = function () {
  76253. return "DeviceOrientationCamera";
  76254. };
  76255. /**
  76256. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  76257. */
  76258. DeviceOrientationCamera.prototype._checkInputs = function () {
  76259. _super.prototype._checkInputs.call(this);
  76260. this._quaternionCache.copyFrom(this.rotationQuaternion);
  76261. if (this._initialQuaternion) {
  76262. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76263. }
  76264. };
  76265. /**
  76266. * Reset the camera to its default orientation on the specified axis only.
  76267. * @param axis The axis to reset
  76268. */
  76269. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  76270. var _this = this;
  76271. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  76272. //can only work if this camera has a rotation quaternion already.
  76273. if (!this.rotationQuaternion)
  76274. return;
  76275. if (!this._initialQuaternion) {
  76276. this._initialQuaternion = new BABYLON.Quaternion();
  76277. }
  76278. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  76279. ['x', 'y', 'z'].forEach(function (axisName) {
  76280. if (!axis[axisName]) {
  76281. _this._initialQuaternion[axisName] = 0;
  76282. }
  76283. else {
  76284. _this._initialQuaternion[axisName] *= -1;
  76285. }
  76286. });
  76287. this._initialQuaternion.normalize();
  76288. //force rotation update
  76289. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76290. };
  76291. return DeviceOrientationCamera;
  76292. }(BABYLON.FreeCamera));
  76293. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  76294. })(BABYLON || (BABYLON = {}));
  76295. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  76296. var BABYLON;
  76297. (function (BABYLON) {
  76298. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  76299. __extends(VRDeviceOrientationFreeCamera, _super);
  76300. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76301. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76302. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76303. var _this = _super.call(this, name, position, scene) || this;
  76304. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76305. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76306. return _this;
  76307. }
  76308. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  76309. return "VRDeviceOrientationFreeCamera";
  76310. };
  76311. return VRDeviceOrientationFreeCamera;
  76312. }(BABYLON.DeviceOrientationCamera));
  76313. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  76314. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  76315. __extends(VRDeviceOrientationGamepadCamera, _super);
  76316. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76317. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76318. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76319. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  76320. _this.inputs.addGamepad();
  76321. return _this;
  76322. }
  76323. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  76324. return "VRDeviceOrientationGamepadCamera";
  76325. };
  76326. return VRDeviceOrientationGamepadCamera;
  76327. }(VRDeviceOrientationFreeCamera));
  76328. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  76329. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  76330. __extends(VRDeviceOrientationArcRotateCamera, _super);
  76331. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  76332. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76333. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76334. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76335. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76336. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76337. _this.inputs.addVRDeviceOrientation();
  76338. return _this;
  76339. }
  76340. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  76341. return "VRDeviceOrientationArcRotateCamera";
  76342. };
  76343. return VRDeviceOrientationArcRotateCamera;
  76344. }(BABYLON.ArcRotateCamera));
  76345. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  76346. })(BABYLON || (BABYLON = {}));
  76347. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  76348. var BABYLON;
  76349. (function (BABYLON) {
  76350. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  76351. __extends(AnaglyphFreeCamera, _super);
  76352. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  76353. var _this = _super.call(this, name, position, scene) || this;
  76354. _this.interaxialDistance = interaxialDistance;
  76355. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76356. return _this;
  76357. }
  76358. AnaglyphFreeCamera.prototype.getClassName = function () {
  76359. return "AnaglyphFreeCamera";
  76360. };
  76361. return AnaglyphFreeCamera;
  76362. }(BABYLON.FreeCamera));
  76363. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  76364. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  76365. __extends(AnaglyphArcRotateCamera, _super);
  76366. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  76367. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76368. _this.interaxialDistance = interaxialDistance;
  76369. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76370. return _this;
  76371. }
  76372. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  76373. return "AnaglyphArcRotateCamera";
  76374. };
  76375. return AnaglyphArcRotateCamera;
  76376. }(BABYLON.ArcRotateCamera));
  76377. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  76378. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  76379. __extends(AnaglyphGamepadCamera, _super);
  76380. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  76381. var _this = _super.call(this, name, position, scene) || this;
  76382. _this.interaxialDistance = interaxialDistance;
  76383. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76384. return _this;
  76385. }
  76386. AnaglyphGamepadCamera.prototype.getClassName = function () {
  76387. return "AnaglyphGamepadCamera";
  76388. };
  76389. return AnaglyphGamepadCamera;
  76390. }(BABYLON.GamepadCamera));
  76391. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  76392. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  76393. __extends(AnaglyphUniversalCamera, _super);
  76394. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  76395. var _this = _super.call(this, name, position, scene) || this;
  76396. _this.interaxialDistance = interaxialDistance;
  76397. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76398. return _this;
  76399. }
  76400. AnaglyphUniversalCamera.prototype.getClassName = function () {
  76401. return "AnaglyphUniversalCamera";
  76402. };
  76403. return AnaglyphUniversalCamera;
  76404. }(BABYLON.UniversalCamera));
  76405. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  76406. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  76407. __extends(StereoscopicFreeCamera, _super);
  76408. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76409. var _this = _super.call(this, name, position, scene) || this;
  76410. _this.interaxialDistance = interaxialDistance;
  76411. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76412. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76413. return _this;
  76414. }
  76415. StereoscopicFreeCamera.prototype.getClassName = function () {
  76416. return "StereoscopicFreeCamera";
  76417. };
  76418. return StereoscopicFreeCamera;
  76419. }(BABYLON.FreeCamera));
  76420. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  76421. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  76422. __extends(StereoscopicArcRotateCamera, _super);
  76423. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  76424. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76425. _this.interaxialDistance = interaxialDistance;
  76426. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76427. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76428. return _this;
  76429. }
  76430. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  76431. return "StereoscopicArcRotateCamera";
  76432. };
  76433. return StereoscopicArcRotateCamera;
  76434. }(BABYLON.ArcRotateCamera));
  76435. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  76436. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  76437. __extends(StereoscopicGamepadCamera, _super);
  76438. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76439. var _this = _super.call(this, name, position, scene) || this;
  76440. _this.interaxialDistance = interaxialDistance;
  76441. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76442. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76443. return _this;
  76444. }
  76445. StereoscopicGamepadCamera.prototype.getClassName = function () {
  76446. return "StereoscopicGamepadCamera";
  76447. };
  76448. return StereoscopicGamepadCamera;
  76449. }(BABYLON.GamepadCamera));
  76450. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  76451. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  76452. __extends(StereoscopicUniversalCamera, _super);
  76453. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76454. var _this = _super.call(this, name, position, scene) || this;
  76455. _this.interaxialDistance = interaxialDistance;
  76456. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76457. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76458. return _this;
  76459. }
  76460. StereoscopicUniversalCamera.prototype.getClassName = function () {
  76461. return "StereoscopicUniversalCamera";
  76462. };
  76463. return StereoscopicUniversalCamera;
  76464. }(BABYLON.UniversalCamera));
  76465. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  76466. })(BABYLON || (BABYLON = {}));
  76467. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  76468. var BABYLON;
  76469. (function (BABYLON) {
  76470. /**
  76471. * Helps to quickly add VR support to an existing scene.
  76472. * See http://doc.babylonjs.com/how_to/webvr_helper
  76473. */
  76474. var VRExperienceHelper = /** @class */ (function () {
  76475. /**
  76476. * Instantiates a VRExperienceHelper.
  76477. * Helps to quickly add VR support to an existing scene.
  76478. * @param scene The scene the VRExperienceHelper belongs to.
  76479. * @param webVROptions Options to modify the vr experience helper's behavior.
  76480. */
  76481. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  76482. if (webVROptions === void 0) { webVROptions = {}; }
  76483. var _this = this;
  76484. this.webVROptions = webVROptions;
  76485. // Can the system support WebVR, even if a headset isn't plugged in?
  76486. this._webVRsupported = false;
  76487. // If WebVR is supported, is a headset plugged in and are we ready to present?
  76488. this._webVRready = false;
  76489. // Are we waiting for the requestPresent callback to complete?
  76490. this._webVRrequesting = false;
  76491. // Are we presenting to the headset right now?
  76492. this._webVRpresenting = false;
  76493. // Are we presenting in the fullscreen fallback?
  76494. this._fullscreenVRpresenting = false;
  76495. /**
  76496. * Observable raised when entering VR.
  76497. */
  76498. this.onEnteringVRObservable = new BABYLON.Observable();
  76499. /**
  76500. * Observable raised when exiting VR.
  76501. */
  76502. this.onExitingVRObservable = new BABYLON.Observable();
  76503. /**
  76504. * Observable raised when controller mesh is loaded.
  76505. */
  76506. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76507. this._useCustomVRButton = false;
  76508. this._teleportationRequested = false;
  76509. this._teleportationEnabledOnLeftController = false;
  76510. this._teleportationEnabledOnRightController = false;
  76511. this._interactionsEnabledOnLeftController = false;
  76512. this._interactionsEnabledOnRightController = false;
  76513. this._leftControllerReady = false;
  76514. this._rightControllerReady = false;
  76515. this._floorMeshesCollection = [];
  76516. this._teleportationAllowed = false;
  76517. this._rotationAllowed = true;
  76518. this._teleportationRequestInitiated = false;
  76519. this._teleportationBackRequestInitiated = false;
  76520. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  76521. this._rotationRightAsked = false;
  76522. this._rotationLeftAsked = false;
  76523. this._isDefaultTeleportationTarget = true;
  76524. this._teleportationFillColor = "#444444";
  76525. this._teleportationBorderColor = "#FFFFFF";
  76526. this._rotationAngle = 0;
  76527. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  76528. this._padSensibilityUp = 0.65;
  76529. this._padSensibilityDown = 0.35;
  76530. /**
  76531. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  76532. */
  76533. this.onNewMeshSelected = new BABYLON.Observable();
  76534. /**
  76535. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  76536. */
  76537. this.onNewMeshPicked = new BABYLON.Observable();
  76538. /**
  76539. * Observable raised before camera teleportation
  76540. */
  76541. this.onBeforeCameraTeleport = new BABYLON.Observable();
  76542. /**
  76543. * Observable raised after camera teleportation
  76544. */
  76545. this.onAfterCameraTeleport = new BABYLON.Observable();
  76546. /**
  76547. * Observable raised when current selected mesh gets unselected
  76548. */
  76549. this.onSelectedMeshUnselected = new BABYLON.Observable();
  76550. /**
  76551. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  76552. */
  76553. this.teleportationEnabled = true;
  76554. this._pointerDownOnMeshAsked = false;
  76555. this._isActionableMesh = false;
  76556. this._teleportationInitialized = false;
  76557. this._interactionsEnabled = false;
  76558. this._interactionsRequested = false;
  76559. this._displayGaze = true;
  76560. this._displayLaserPointer = true;
  76561. this._dpadPressed = true;
  76562. this._onResize = function () {
  76563. _this.moveButtonToBottomRight();
  76564. if (_this._fullscreenVRpresenting && _this._webVRready) {
  76565. _this.exitVR();
  76566. }
  76567. };
  76568. this._onFullscreenChange = function () {
  76569. if (document.fullscreen !== undefined) {
  76570. _this._fullscreenVRpresenting = document.fullscreen;
  76571. }
  76572. else if (document.mozFullScreen !== undefined) {
  76573. _this._fullscreenVRpresenting = document.mozFullScreen;
  76574. }
  76575. else if (document.webkitIsFullScreen !== undefined) {
  76576. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  76577. }
  76578. else if (document.msIsFullScreen !== undefined) {
  76579. _this._fullscreenVRpresenting = document.msIsFullScreen;
  76580. }
  76581. if (!_this._fullscreenVRpresenting && _this._canvas) {
  76582. _this.exitVR();
  76583. if (!_this._useCustomVRButton) {
  76584. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  76585. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  76586. }
  76587. }
  76588. };
  76589. this.beforeRender = function () {
  76590. _this._castRayAndSelectObject();
  76591. };
  76592. this._onNewGamepadConnected = function (gamepad) {
  76593. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76594. if (gamepad.leftStick) {
  76595. gamepad.onleftstickchanged(function (stickValues) {
  76596. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  76597. // Listening to classic/xbox gamepad only if no VR controller is active
  76598. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  76599. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  76600. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  76601. _this._checkTeleportWithRay(stickValues);
  76602. _this._checkTeleportBackwards(stickValues);
  76603. }
  76604. }
  76605. });
  76606. }
  76607. if (gamepad.rightStick) {
  76608. gamepad.onrightstickchanged(function (stickValues) {
  76609. if (_this._teleportationInitialized) {
  76610. _this._checkRotate(stickValues);
  76611. }
  76612. });
  76613. }
  76614. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  76615. gamepad.onbuttondown(function (buttonPressed) {
  76616. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76617. _this._selectionPointerDown();
  76618. }
  76619. });
  76620. gamepad.onbuttonup(function (buttonPressed) {
  76621. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76622. _this._selectionPointerUp();
  76623. }
  76624. });
  76625. }
  76626. }
  76627. else {
  76628. var webVRController = gamepad;
  76629. _this._tryEnableInteractionOnController(webVRController);
  76630. }
  76631. };
  76632. // 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
  76633. this._tryEnableInteractionOnController = function (webVRController) {
  76634. if (webVRController.hand === "left") {
  76635. _this._leftControllerReady = true;
  76636. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  76637. _this._enableInteractionOnController(webVRController);
  76638. }
  76639. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  76640. _this._enableTeleportationOnController(webVRController);
  76641. }
  76642. }
  76643. if (webVRController.hand === "right") {
  76644. _this._rightControllerReady = true;
  76645. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  76646. _this._enableInteractionOnController(webVRController);
  76647. }
  76648. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  76649. _this._enableTeleportationOnController(webVRController);
  76650. }
  76651. }
  76652. };
  76653. this._onNewGamepadDisconnected = function (gamepad) {
  76654. if (gamepad instanceof BABYLON.WebVRController) {
  76655. if (gamepad.hand === "left") {
  76656. _this._interactionsEnabledOnLeftController = false;
  76657. _this._teleportationEnabledOnLeftController = false;
  76658. _this._leftControllerReady = false;
  76659. if (_this._leftLaserPointer) {
  76660. _this._leftLaserPointer.dispose();
  76661. }
  76662. }
  76663. if (gamepad.hand === "right") {
  76664. _this._interactionsEnabledOnRightController = false;
  76665. _this._teleportationEnabledOnRightController = false;
  76666. _this._rightControllerReady = false;
  76667. if (_this._rightLaserPointer) {
  76668. _this._rightLaserPointer.dispose();
  76669. }
  76670. }
  76671. }
  76672. };
  76673. this._workingVector = BABYLON.Vector3.Zero();
  76674. this._workingQuaternion = BABYLON.Quaternion.Identity();
  76675. this._workingMatrix = BABYLON.Matrix.Identity();
  76676. this._scene = scene;
  76677. this._canvas = scene.getEngine().getRenderingCanvas();
  76678. // Parse options
  76679. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  76680. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  76681. }
  76682. if (webVROptions.createDeviceOrientationCamera === undefined) {
  76683. webVROptions.createDeviceOrientationCamera = true;
  76684. }
  76685. if (webVROptions.defaultHeight === undefined) {
  76686. webVROptions.defaultHeight = 1.7;
  76687. }
  76688. if (webVROptions.useCustomVRButton) {
  76689. this._useCustomVRButton = true;
  76690. if (webVROptions.customVRButton) {
  76691. this._btnVR = webVROptions.customVRButton;
  76692. }
  76693. }
  76694. if (webVROptions.rayLength) {
  76695. this._rayLength = webVROptions.rayLength;
  76696. }
  76697. this._defaultHeight = webVROptions.defaultHeight;
  76698. // Set position
  76699. if (this._scene.activeCamera) {
  76700. this._position = this._scene.activeCamera.position.clone();
  76701. }
  76702. else {
  76703. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  76704. }
  76705. // Set non-vr camera
  76706. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  76707. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  76708. // Copy data from existing camera
  76709. if (this._scene.activeCamera) {
  76710. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  76711. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  76712. // Set rotation from previous camera
  76713. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  76714. var targetCamera = this._scene.activeCamera;
  76715. if (targetCamera.rotationQuaternion) {
  76716. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  76717. }
  76718. else {
  76719. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  76720. }
  76721. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  76722. }
  76723. }
  76724. this._scene.activeCamera = this._deviceOrientationCamera;
  76725. if (this._canvas) {
  76726. this._scene.activeCamera.attachControl(this._canvas);
  76727. }
  76728. }
  76729. else {
  76730. this._existingCamera = this._scene.activeCamera;
  76731. }
  76732. // Create VR cameras
  76733. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76734. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  76735. }
  76736. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  76737. this._webVRCamera.useStandingMatrix();
  76738. // Create default button
  76739. if (!this._useCustomVRButton) {
  76740. this._btnVR = document.createElement("BUTTON");
  76741. this._btnVR.className = "babylonVRicon";
  76742. this._btnVR.id = "babylonVRiconbtn";
  76743. this._btnVR.title = "Click to switch to VR";
  76744. 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) }";
  76745. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  76746. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  76747. // css += ".babylonVRicon.vrdisplaysupported { }";
  76748. // css += ".babylonVRicon.vrdisplayready { }";
  76749. // css += ".babylonVRicon.vrdisplayrequesting { }";
  76750. var style = document.createElement('style');
  76751. style.appendChild(document.createTextNode(css));
  76752. document.getElementsByTagName('head')[0].appendChild(style);
  76753. this.moveButtonToBottomRight();
  76754. }
  76755. // VR button click event
  76756. if (this._btnVR) {
  76757. this._btnVR.addEventListener("click", function () {
  76758. if (!_this.isInVRMode) {
  76759. _this.enterVR();
  76760. }
  76761. else {
  76762. _this.exitVR();
  76763. }
  76764. });
  76765. }
  76766. // Window events
  76767. window.addEventListener("resize", this._onResize);
  76768. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  76769. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  76770. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  76771. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  76772. // Display vr button when headset is connected
  76773. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76774. this.displayVRButton();
  76775. }
  76776. else {
  76777. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  76778. if (e.vrDisplay) {
  76779. _this.displayVRButton();
  76780. }
  76781. });
  76782. }
  76783. // Exiting VR mode using 'ESC' key on desktop
  76784. this._onKeyDown = function (event) {
  76785. if (event.keyCode === 27 && _this.isInVRMode) {
  76786. _this.exitVR();
  76787. }
  76788. };
  76789. document.addEventListener("keydown", this._onKeyDown);
  76790. // Exiting VR mode double tapping the touch screen
  76791. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  76792. if (_this.isInVRMode) {
  76793. _this.exitVR();
  76794. if (_this._fullscreenVRpresenting) {
  76795. _this._scene.getEngine().switchFullscreen(true);
  76796. }
  76797. }
  76798. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  76799. // Listen for WebVR display changes
  76800. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  76801. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  76802. this._onVRRequestPresentStart = function () {
  76803. _this._webVRrequesting = true;
  76804. _this.updateButtonVisibility();
  76805. };
  76806. this._onVRRequestPresentComplete = function (success) {
  76807. _this._webVRrequesting = false;
  76808. _this.updateButtonVisibility();
  76809. };
  76810. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  76811. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  76812. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  76813. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76814. scene.onDisposeObservable.add(function () {
  76815. _this.dispose();
  76816. });
  76817. // Gamepad connection events
  76818. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  76819. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  76820. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  76821. this.updateButtonVisibility();
  76822. //create easing functions
  76823. this._circleEase = new BABYLON.CircleEase();
  76824. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76825. }
  76826. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  76827. /** Return this.onEnteringVRObservable
  76828. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  76829. */
  76830. get: function () {
  76831. return this.onEnteringVRObservable;
  76832. },
  76833. enumerable: true,
  76834. configurable: true
  76835. });
  76836. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  76837. /** Return this.onExitingVRObservable
  76838. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  76839. */
  76840. get: function () {
  76841. return this.onExitingVRObservable;
  76842. },
  76843. enumerable: true,
  76844. configurable: true
  76845. });
  76846. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  76847. /** Return this.onControllerMeshLoadedObservable
  76848. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  76849. */
  76850. get: function () {
  76851. return this.onControllerMeshLoadedObservable;
  76852. },
  76853. enumerable: true,
  76854. configurable: true
  76855. });
  76856. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  76857. /**
  76858. * The mesh used to display where the user is going to teleport.
  76859. */
  76860. get: function () {
  76861. return this._teleportationTarget;
  76862. },
  76863. /**
  76864. * Sets the mesh to be used to display where the user is going to teleport.
  76865. */
  76866. set: function (value) {
  76867. if (value) {
  76868. value.name = "teleportationTarget";
  76869. this._isDefaultTeleportationTarget = false;
  76870. this._teleportationTarget = value;
  76871. }
  76872. },
  76873. enumerable: true,
  76874. configurable: true
  76875. });
  76876. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  76877. /**
  76878. * If the ray of the gaze should be displayed.
  76879. */
  76880. get: function () {
  76881. return this._displayGaze;
  76882. },
  76883. /**
  76884. * Sets if the ray of the gaze should be displayed.
  76885. */
  76886. set: function (value) {
  76887. this._displayGaze = value;
  76888. if (!value) {
  76889. this._gazeTracker.isVisible = false;
  76890. }
  76891. },
  76892. enumerable: true,
  76893. configurable: true
  76894. });
  76895. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  76896. /**
  76897. * If the ray of the LaserPointer should be displayed.
  76898. */
  76899. get: function () {
  76900. return this._displayLaserPointer;
  76901. },
  76902. /**
  76903. * Sets if the ray of the LaserPointer should be displayed.
  76904. */
  76905. set: function (value) {
  76906. this._displayLaserPointer = value;
  76907. if (!value) {
  76908. if (this._rightLaserPointer) {
  76909. this._rightLaserPointer.isVisible = false;
  76910. }
  76911. if (this._leftLaserPointer) {
  76912. this._leftLaserPointer.isVisible = false;
  76913. }
  76914. }
  76915. else {
  76916. if (this._rightLaserPointer) {
  76917. this._rightLaserPointer.isVisible = true;
  76918. }
  76919. else if (this._leftLaserPointer) {
  76920. this._leftLaserPointer.isVisible = true;
  76921. }
  76922. }
  76923. },
  76924. enumerable: true,
  76925. configurable: true
  76926. });
  76927. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  76928. /**
  76929. * The deviceOrientationCamera used as the camera when not in VR.
  76930. */
  76931. get: function () {
  76932. return this._deviceOrientationCamera;
  76933. },
  76934. enumerable: true,
  76935. configurable: true
  76936. });
  76937. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  76938. /**
  76939. * Based on the current WebVR support, returns the current VR camera used.
  76940. */
  76941. get: function () {
  76942. if (this._webVRready) {
  76943. return this._webVRCamera;
  76944. }
  76945. else {
  76946. return this._scene.activeCamera;
  76947. }
  76948. },
  76949. enumerable: true,
  76950. configurable: true
  76951. });
  76952. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  76953. /**
  76954. * The webVRCamera which is used when in VR.
  76955. */
  76956. get: function () {
  76957. return this._webVRCamera;
  76958. },
  76959. enumerable: true,
  76960. configurable: true
  76961. });
  76962. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  76963. /**
  76964. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  76965. */
  76966. get: function () {
  76967. return this._vrDeviceOrientationCamera;
  76968. },
  76969. enumerable: true,
  76970. configurable: true
  76971. });
  76972. // Raised when one of the controller has loaded successfully its associated default mesh
  76973. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  76974. this._tryEnableInteractionOnController(webVRController);
  76975. try {
  76976. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  76977. }
  76978. catch (err) {
  76979. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  76980. }
  76981. };
  76982. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  76983. /**
  76984. * Gets a value indicating if we are currently in VR mode.
  76985. */
  76986. get: function () {
  76987. return this._webVRpresenting || this._fullscreenVRpresenting;
  76988. },
  76989. enumerable: true,
  76990. configurable: true
  76991. });
  76992. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  76993. var vrDisplay = this._scene.getEngine().getVRDevice();
  76994. if (vrDisplay) {
  76995. var wasPresenting = this._webVRpresenting;
  76996. // A VR display is connected
  76997. this._webVRpresenting = vrDisplay.isPresenting;
  76998. if (wasPresenting && !this._webVRpresenting)
  76999. this.exitVR();
  77000. }
  77001. else {
  77002. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  77003. }
  77004. this.updateButtonVisibility();
  77005. };
  77006. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  77007. this._webVRsupported = eventArgs.vrSupported;
  77008. this._webVRready = !!eventArgs.vrDisplay;
  77009. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  77010. this.updateButtonVisibility();
  77011. };
  77012. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  77013. if (this._canvas && !this._useCustomVRButton) {
  77014. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  77015. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  77016. }
  77017. };
  77018. VRExperienceHelper.prototype.displayVRButton = function () {
  77019. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  77020. document.body.appendChild(this._btnVR);
  77021. this._btnVRDisplayed = true;
  77022. }
  77023. };
  77024. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  77025. if (!this._btnVR || this._useCustomVRButton) {
  77026. return;
  77027. }
  77028. this._btnVR.className = "babylonVRicon";
  77029. if (this.isInVRMode) {
  77030. this._btnVR.className += " vrdisplaypresenting";
  77031. }
  77032. else {
  77033. if (this._webVRready)
  77034. this._btnVR.className += " vrdisplayready";
  77035. if (this._webVRsupported)
  77036. this._btnVR.className += " vrdisplaysupported";
  77037. if (this._webVRrequesting)
  77038. this._btnVR.className += " vrdisplayrequesting";
  77039. }
  77040. };
  77041. /**
  77042. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  77043. * Otherwise, will use the fullscreen API.
  77044. */
  77045. VRExperienceHelper.prototype.enterVR = function () {
  77046. if (this.onEnteringVRObservable) {
  77047. try {
  77048. this.onEnteringVRObservable.notifyObservers(this);
  77049. }
  77050. catch (err) {
  77051. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  77052. }
  77053. }
  77054. if (this._scene.activeCamera) {
  77055. this._position = this._scene.activeCamera.position.clone();
  77056. // make sure that we return to the last active camera
  77057. this._existingCamera = this._scene.activeCamera;
  77058. }
  77059. if (this._webVRrequesting)
  77060. return;
  77061. // If WebVR is supported and a headset is connected
  77062. if (this._webVRready) {
  77063. if (!this._webVRpresenting) {
  77064. this._webVRCamera.position = this._position;
  77065. this._scene.activeCamera = this._webVRCamera;
  77066. }
  77067. }
  77068. else if (this._vrDeviceOrientationCamera) {
  77069. this._vrDeviceOrientationCamera.position = this._position;
  77070. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  77071. this._scene.getEngine().switchFullscreen(true);
  77072. this.updateButtonVisibility();
  77073. }
  77074. if (this._scene.activeCamera && this._canvas) {
  77075. this._scene.activeCamera.attachControl(this._canvas);
  77076. }
  77077. if (this._interactionsEnabled) {
  77078. this._scene.registerBeforeRender(this.beforeRender);
  77079. }
  77080. };
  77081. /**
  77082. * Attempt to exit VR, or fullscreen.
  77083. */
  77084. VRExperienceHelper.prototype.exitVR = function () {
  77085. if (this.onExitingVRObservable) {
  77086. try {
  77087. this.onExitingVRObservable.notifyObservers(this);
  77088. }
  77089. catch (err) {
  77090. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  77091. }
  77092. }
  77093. if (this._webVRpresenting) {
  77094. this._scene.getEngine().disableVR();
  77095. }
  77096. if (this._scene.activeCamera) {
  77097. this._position = this._scene.activeCamera.position.clone();
  77098. }
  77099. if (this._deviceOrientationCamera) {
  77100. this._deviceOrientationCamera.position = this._position;
  77101. this._scene.activeCamera = this._deviceOrientationCamera;
  77102. if (this._canvas) {
  77103. this._scene.activeCamera.attachControl(this._canvas);
  77104. }
  77105. }
  77106. else if (this._existingCamera) {
  77107. this._existingCamera.position = this._position;
  77108. this._scene.activeCamera = this._existingCamera;
  77109. }
  77110. this.updateButtonVisibility();
  77111. if (this._interactionsEnabled) {
  77112. this._scene.unregisterBeforeRender(this.beforeRender);
  77113. }
  77114. };
  77115. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  77116. /**
  77117. * The position of the vr experience helper.
  77118. */
  77119. get: function () {
  77120. return this._position;
  77121. },
  77122. /**
  77123. * Sets the position of the vr experience helper.
  77124. */
  77125. set: function (value) {
  77126. this._position = value;
  77127. if (this._scene.activeCamera) {
  77128. this._scene.activeCamera.position = value;
  77129. }
  77130. },
  77131. enumerable: true,
  77132. configurable: true
  77133. });
  77134. /**
  77135. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  77136. */
  77137. VRExperienceHelper.prototype.enableInteractions = function () {
  77138. var _this = this;
  77139. if (!this._interactionsEnabled) {
  77140. this._interactionsRequested = true;
  77141. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77142. this._enableInteractionOnController(this._webVRCamera.leftController);
  77143. }
  77144. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77145. this._enableInteractionOnController(this._webVRCamera.rightController);
  77146. }
  77147. this._createGazeTracker();
  77148. this.raySelectionPredicate = function (mesh) {
  77149. return mesh.isVisible;
  77150. };
  77151. this.meshSelectionPredicate = function (mesh) {
  77152. return true;
  77153. };
  77154. this._raySelectionPredicate = function (mesh) {
  77155. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  77156. && mesh.name.indexOf("teleportationTarget") === -1
  77157. && mesh.name.indexOf("torusTeleportation") === -1
  77158. && mesh.name.indexOf("laserPointer") === -1)) {
  77159. return _this.raySelectionPredicate(mesh);
  77160. }
  77161. return false;
  77162. };
  77163. this._interactionsEnabled = true;
  77164. }
  77165. };
  77166. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  77167. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  77168. if (this._floorMeshesCollection[i].id === mesh.id) {
  77169. return true;
  77170. }
  77171. }
  77172. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  77173. return true;
  77174. }
  77175. return false;
  77176. };
  77177. /**
  77178. * Adds a floor mesh to be used for teleportation.
  77179. * @param floorMesh the mesh to be used for teleportation.
  77180. */
  77181. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  77182. if (!this._floorMeshesCollection) {
  77183. return;
  77184. }
  77185. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  77186. return;
  77187. }
  77188. this._floorMeshesCollection.push(floorMesh);
  77189. };
  77190. /**
  77191. * Removes a floor mesh from being used for teleportation.
  77192. * @param floorMesh the mesh to be removed.
  77193. */
  77194. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  77195. if (!this._floorMeshesCollection) {
  77196. return;
  77197. }
  77198. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  77199. if (meshIndex !== -1) {
  77200. this._floorMeshesCollection.splice(meshIndex, 1);
  77201. }
  77202. };
  77203. /**
  77204. * Enables interactions and teleportation using the VR controllers and gaze.
  77205. * @param vrTeleportationOptions options to modify teleportation behavior.
  77206. */
  77207. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  77208. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  77209. if (!this._teleportationInitialized) {
  77210. this._teleportationRequested = true;
  77211. this.enableInteractions();
  77212. if (vrTeleportationOptions.floorMeshName) {
  77213. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  77214. }
  77215. if (vrTeleportationOptions.floorMeshes) {
  77216. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  77217. }
  77218. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77219. this._enableTeleportationOnController(this._webVRCamera.leftController);
  77220. }
  77221. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77222. this._enableTeleportationOnController(this._webVRCamera.rightController);
  77223. }
  77224. // Creates an image processing post process for the vignette not relying
  77225. // on the main scene configuration for image processing to reduce setup and spaces
  77226. // (gamma/linear) conflicts.
  77227. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  77228. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77229. imageProcessingConfiguration.vignetteEnabled = true;
  77230. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  77231. this._webVRCamera.detachPostProcess(this._postProcessMove);
  77232. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  77233. this._teleportationInitialized = true;
  77234. if (this._isDefaultTeleportationTarget) {
  77235. this._createTeleportationCircles();
  77236. }
  77237. }
  77238. };
  77239. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  77240. var _this = this;
  77241. var controllerMesh = webVRController.mesh;
  77242. if (controllerMesh) {
  77243. var makeNotPick = function (root) {
  77244. root.name += " laserPointer";
  77245. root.getChildMeshes().forEach(function (c) {
  77246. makeNotPick(c);
  77247. });
  77248. };
  77249. makeNotPick(controllerMesh);
  77250. var childMeshes = controllerMesh.getChildMeshes();
  77251. for (var i = 0; i < childMeshes.length; i++) {
  77252. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  77253. controllerMesh = childMeshes[i];
  77254. break;
  77255. }
  77256. }
  77257. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  77258. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  77259. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77260. laserPointerMaterial.alpha = 0.6;
  77261. laserPointer.material = laserPointerMaterial;
  77262. laserPointer.rotation.x = Math.PI / 2;
  77263. laserPointer.parent = controllerMesh;
  77264. laserPointer.position.z = -0.5;
  77265. laserPointer.isVisible = false;
  77266. if (webVRController.hand === "left") {
  77267. this._leftLaserPointer = laserPointer;
  77268. this._interactionsEnabledOnLeftController = true;
  77269. if (!this._rightLaserPointer) {
  77270. this._leftLaserPointer.isVisible = true;
  77271. }
  77272. }
  77273. else {
  77274. this._rightLaserPointer = laserPointer;
  77275. this._interactionsEnabledOnRightController = true;
  77276. if (!this._leftLaserPointer) {
  77277. this._rightLaserPointer.isVisible = true;
  77278. }
  77279. }
  77280. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  77281. // Enabling / disabling laserPointer
  77282. if (_this._displayLaserPointer && stateObject.value === 1) {
  77283. laserPointer.isVisible = !laserPointer.isVisible;
  77284. // Laser pointer can only be active on left or right, not both at the same time
  77285. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  77286. _this._rightLaserPointer.isVisible = false;
  77287. }
  77288. else if (_this._leftLaserPointer) {
  77289. _this._leftLaserPointer.isVisible = false;
  77290. }
  77291. }
  77292. });
  77293. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  77294. if (!_this._pointerDownOnMeshAsked) {
  77295. if (stateObject.value > _this._padSensibilityUp) {
  77296. _this._selectionPointerDown();
  77297. }
  77298. }
  77299. else if (stateObject.value < _this._padSensibilityDown) {
  77300. _this._selectionPointerUp();
  77301. }
  77302. });
  77303. }
  77304. };
  77305. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  77306. if (webVRController === void 0) { webVRController = null; }
  77307. if (!this._teleportationRequestInitiated) {
  77308. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  77309. if (webVRController) {
  77310. // If laser pointer wasn't enabled yet
  77311. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  77312. this._leftLaserPointer.isVisible = true;
  77313. if (this._rightLaserPointer) {
  77314. this._rightLaserPointer.isVisible = false;
  77315. }
  77316. }
  77317. else if (this._displayLaserPointer && this._rightLaserPointer) {
  77318. this._rightLaserPointer.isVisible = true;
  77319. if (this._leftLaserPointer) {
  77320. this._leftLaserPointer.isVisible = false;
  77321. }
  77322. }
  77323. }
  77324. this._teleportationRequestInitiated = true;
  77325. }
  77326. }
  77327. else {
  77328. // Listening to the proper controller values changes to confirm teleportation
  77329. if (webVRController == null
  77330. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  77331. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  77332. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  77333. if (this._teleportationAllowed) {
  77334. this._teleportationAllowed = false;
  77335. this._teleportCamera();
  77336. }
  77337. this._teleportationRequestInitiated = false;
  77338. }
  77339. }
  77340. }
  77341. };
  77342. VRExperienceHelper.prototype._selectionPointerDown = function () {
  77343. this._pointerDownOnMeshAsked = true;
  77344. if (this._currentMeshSelected && this._currentHit) {
  77345. this._scene.simulatePointerDown(this._currentHit);
  77346. }
  77347. };
  77348. VRExperienceHelper.prototype._selectionPointerUp = function () {
  77349. if (this._currentMeshSelected && this._currentHit) {
  77350. this._scene.simulatePointerUp(this._currentHit);
  77351. }
  77352. this._pointerDownOnMeshAsked = false;
  77353. };
  77354. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  77355. // Only rotate when user is not currently selecting a teleportation location
  77356. if (this._teleportationRequestInitiated) {
  77357. return;
  77358. }
  77359. if (!this._rotationLeftAsked) {
  77360. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  77361. this._rotationLeftAsked = true;
  77362. if (this._rotationAllowed) {
  77363. this._rotateCamera(false);
  77364. }
  77365. }
  77366. }
  77367. else {
  77368. if (stateObject.x > -this._padSensibilityDown) {
  77369. this._rotationLeftAsked = false;
  77370. }
  77371. }
  77372. if (!this._rotationRightAsked) {
  77373. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  77374. this._rotationRightAsked = true;
  77375. if (this._rotationAllowed) {
  77376. this._rotateCamera(true);
  77377. }
  77378. }
  77379. }
  77380. else {
  77381. if (stateObject.x < this._padSensibilityDown) {
  77382. this._rotationRightAsked = false;
  77383. }
  77384. }
  77385. };
  77386. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  77387. // Only teleport backwards when user is not currently selecting a teleportation location
  77388. if (this._teleportationRequestInitiated) {
  77389. return;
  77390. }
  77391. // Teleport backwards
  77392. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  77393. if (!this._teleportationBackRequestInitiated) {
  77394. if (!this.currentVRCamera) {
  77395. return;
  77396. }
  77397. // Get rotation and position of the current camera
  77398. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  77399. var position = this.currentVRCamera.position;
  77400. // If the camera has device position, use that instead
  77401. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  77402. rotation = this.currentVRCamera.deviceRotationQuaternion;
  77403. position = this.currentVRCamera.devicePosition;
  77404. }
  77405. // Get matrix with only the y rotation of the device rotation
  77406. rotation.toEulerAnglesToRef(this._workingVector);
  77407. this._workingVector.z = 0;
  77408. this._workingVector.x = 0;
  77409. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  77410. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  77411. // Rotate backwards ray by device rotation to cast at the ground behind the user
  77412. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  77413. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  77414. var ray = new BABYLON.Ray(position, this._workingVector);
  77415. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77416. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  77417. this._teleportCamera(hit.pickedPoint);
  77418. }
  77419. this._teleportationBackRequestInitiated = true;
  77420. }
  77421. }
  77422. else {
  77423. this._teleportationBackRequestInitiated = false;
  77424. }
  77425. };
  77426. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  77427. var _this = this;
  77428. var controllerMesh = webVRController.mesh;
  77429. if (controllerMesh) {
  77430. if (webVRController.hand === "left") {
  77431. if (!this._interactionsEnabledOnLeftController) {
  77432. this._enableInteractionOnController(webVRController);
  77433. }
  77434. this._teleportationEnabledOnLeftController = true;
  77435. }
  77436. else {
  77437. if (!this._interactionsEnabledOnRightController) {
  77438. this._enableInteractionOnController(webVRController);
  77439. }
  77440. this._teleportationEnabledOnRightController = true;
  77441. }
  77442. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77443. this._dpadPressed = false;
  77444. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  77445. _this._dpadPressed = stateObject.pressed;
  77446. if (!_this._dpadPressed) {
  77447. _this._rotationLeftAsked = false;
  77448. _this._rotationRightAsked = false;
  77449. _this._teleportationBackRequestInitiated = false;
  77450. }
  77451. });
  77452. }
  77453. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  77454. if (_this.teleportationEnabled) {
  77455. _this._checkTeleportBackwards(stateObject);
  77456. _this._checkTeleportWithRay(stateObject, webVRController);
  77457. }
  77458. _this._checkRotate(stateObject);
  77459. });
  77460. }
  77461. };
  77462. // Gaze support used to point to teleport or to interact with an object
  77463. VRExperienceHelper.prototype._createGazeTracker = function () {
  77464. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  77465. this._gazeTracker.bakeCurrentTransformIntoVertices();
  77466. this._gazeTracker.isPickable = false;
  77467. this._gazeTracker.isVisible = false;
  77468. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  77469. targetMat.specularColor = BABYLON.Color3.Black();
  77470. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77471. targetMat.backFaceCulling = false;
  77472. this._gazeTracker.material = targetMat;
  77473. };
  77474. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  77475. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  77476. this._teleportationTarget.isPickable = false;
  77477. var length = 512;
  77478. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  77479. dynamicTexture.hasAlpha = true;
  77480. var context = dynamicTexture.getContext();
  77481. var centerX = length / 2;
  77482. var centerY = length / 2;
  77483. var radius = 200;
  77484. context.beginPath();
  77485. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  77486. context.fillStyle = this._teleportationFillColor;
  77487. context.fill();
  77488. context.lineWidth = 10;
  77489. context.strokeStyle = this._teleportationBorderColor;
  77490. context.stroke();
  77491. context.closePath();
  77492. dynamicTexture.update();
  77493. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  77494. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  77495. this._teleportationTarget.material = teleportationCircleMaterial;
  77496. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  77497. torus.isPickable = false;
  77498. torus.parent = this._teleportationTarget;
  77499. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77500. var keys = [];
  77501. keys.push({
  77502. frame: 0,
  77503. value: 0
  77504. });
  77505. keys.push({
  77506. frame: 30,
  77507. value: 0.4
  77508. });
  77509. keys.push({
  77510. frame: 60,
  77511. value: 0
  77512. });
  77513. animationInnerCircle.setKeys(keys);
  77514. var easingFunction = new BABYLON.SineEase();
  77515. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77516. animationInnerCircle.setEasingFunction(easingFunction);
  77517. torus.animations = [];
  77518. torus.animations.push(animationInnerCircle);
  77519. this._scene.beginAnimation(torus, 0, 60, true);
  77520. this._hideTeleportationTarget();
  77521. };
  77522. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  77523. if (this._teleportationInitialized) {
  77524. this._teleportationTarget.isVisible = true;
  77525. if (this._isDefaultTeleportationTarget) {
  77526. this._teleportationTarget.getChildren()[0].isVisible = true;
  77527. }
  77528. }
  77529. };
  77530. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  77531. if (this._teleportationInitialized) {
  77532. this._teleportationTarget.isVisible = false;
  77533. if (this._isDefaultTeleportationTarget) {
  77534. this._teleportationTarget.getChildren()[0].isVisible = false;
  77535. }
  77536. }
  77537. };
  77538. VRExperienceHelper.prototype._rotateCamera = function (right) {
  77539. var _this = this;
  77540. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77541. return;
  77542. }
  77543. if (right) {
  77544. this._rotationAngle++;
  77545. }
  77546. else {
  77547. this._rotationAngle--;
  77548. }
  77549. this.currentVRCamera.animations = [];
  77550. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  77551. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77552. var animationRotationKeys = [];
  77553. animationRotationKeys.push({
  77554. frame: 0,
  77555. value: this.currentVRCamera.rotationQuaternion
  77556. });
  77557. animationRotationKeys.push({
  77558. frame: 6,
  77559. value: target
  77560. });
  77561. animationRotation.setKeys(animationRotationKeys);
  77562. animationRotation.setEasingFunction(this._circleEase);
  77563. this.currentVRCamera.animations.push(animationRotation);
  77564. this._postProcessMove.animations = [];
  77565. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77566. var vignetteWeightKeys = [];
  77567. vignetteWeightKeys.push({
  77568. frame: 0,
  77569. value: 0
  77570. });
  77571. vignetteWeightKeys.push({
  77572. frame: 3,
  77573. value: 4
  77574. });
  77575. vignetteWeightKeys.push({
  77576. frame: 6,
  77577. value: 0
  77578. });
  77579. animationPP.setKeys(vignetteWeightKeys);
  77580. animationPP.setEasingFunction(this._circleEase);
  77581. this._postProcessMove.animations.push(animationPP);
  77582. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77583. var vignetteStretchKeys = [];
  77584. vignetteStretchKeys.push({
  77585. frame: 0,
  77586. value: 0
  77587. });
  77588. vignetteStretchKeys.push({
  77589. frame: 3,
  77590. value: 10
  77591. });
  77592. vignetteStretchKeys.push({
  77593. frame: 6,
  77594. value: 0
  77595. });
  77596. animationPP2.setKeys(vignetteStretchKeys);
  77597. animationPP2.setEasingFunction(this._circleEase);
  77598. this._postProcessMove.animations.push(animationPP2);
  77599. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77600. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77601. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77602. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  77603. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77604. });
  77605. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  77606. };
  77607. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  77608. if (hit.pickedPoint) {
  77609. this._teleportationAllowed = true;
  77610. if (this._teleportationRequestInitiated) {
  77611. this._displayTeleportationTarget();
  77612. }
  77613. else {
  77614. this._hideTeleportationTarget();
  77615. }
  77616. this._haloCenter.copyFrom(hit.pickedPoint);
  77617. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  77618. var pickNormal = hit.getNormal(true, false);
  77619. if (pickNormal) {
  77620. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77621. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77622. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  77623. }
  77624. this._teleportationTarget.position.y += 0.1;
  77625. }
  77626. };
  77627. VRExperienceHelper.prototype._teleportCamera = function (location) {
  77628. var _this = this;
  77629. if (location === void 0) { location = null; }
  77630. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77631. return;
  77632. }
  77633. if (!location) {
  77634. location = this._haloCenter;
  77635. }
  77636. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  77637. // offset of the headset from the anchor.
  77638. if (this.webVRCamera.leftCamera) {
  77639. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  77640. this._workingVector.subtractInPlace(this.webVRCamera.position);
  77641. location.subtractToRef(this._workingVector, this._workingVector);
  77642. }
  77643. else {
  77644. this._workingVector.copyFrom(location);
  77645. }
  77646. // Add height to account for user's height offset
  77647. if (this.isInVRMode) {
  77648. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  77649. }
  77650. else {
  77651. this._workingVector.y += this._defaultHeight;
  77652. }
  77653. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  77654. // Create animation from the camera's position to the new location
  77655. this.currentVRCamera.animations = [];
  77656. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77657. var animationCameraTeleportationKeys = [{
  77658. frame: 0,
  77659. value: this.currentVRCamera.position
  77660. },
  77661. {
  77662. frame: 11,
  77663. value: this._workingVector
  77664. }
  77665. ];
  77666. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  77667. animationCameraTeleportation.setEasingFunction(this._circleEase);
  77668. this.currentVRCamera.animations.push(animationCameraTeleportation);
  77669. this._postProcessMove.animations = [];
  77670. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77671. var vignetteWeightKeys = [];
  77672. vignetteWeightKeys.push({
  77673. frame: 0,
  77674. value: 0
  77675. });
  77676. vignetteWeightKeys.push({
  77677. frame: 5,
  77678. value: 8
  77679. });
  77680. vignetteWeightKeys.push({
  77681. frame: 11,
  77682. value: 0
  77683. });
  77684. animationPP.setKeys(vignetteWeightKeys);
  77685. this._postProcessMove.animations.push(animationPP);
  77686. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77687. var vignetteStretchKeys = [];
  77688. vignetteStretchKeys.push({
  77689. frame: 0,
  77690. value: 0
  77691. });
  77692. vignetteStretchKeys.push({
  77693. frame: 5,
  77694. value: 10
  77695. });
  77696. vignetteStretchKeys.push({
  77697. frame: 11,
  77698. value: 0
  77699. });
  77700. animationPP2.setKeys(vignetteStretchKeys);
  77701. this._postProcessMove.animations.push(animationPP2);
  77702. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77703. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77704. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77705. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  77706. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77707. });
  77708. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  77709. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  77710. });
  77711. };
  77712. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  77713. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77714. return;
  77715. }
  77716. var ray;
  77717. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  77718. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  77719. }
  77720. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  77721. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  77722. }
  77723. else {
  77724. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  77725. }
  77726. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77727. // Moving the gazeTracker on the mesh face targetted
  77728. if (hit && hit.pickedPoint) {
  77729. if (this._displayGaze) {
  77730. var multiplier = 1;
  77731. this._gazeTracker.isVisible = true;
  77732. if (this._isActionableMesh) {
  77733. multiplier = 3;
  77734. }
  77735. this._gazeTracker.scaling.x = hit.distance * multiplier;
  77736. this._gazeTracker.scaling.y = hit.distance * multiplier;
  77737. this._gazeTracker.scaling.z = hit.distance * multiplier;
  77738. var pickNormal = hit.getNormal();
  77739. // To avoid z-fighting
  77740. var deltaFighting = 0.002;
  77741. if (pickNormal) {
  77742. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77743. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77744. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  77745. }
  77746. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  77747. if (this._gazeTracker.position.x < 0) {
  77748. this._gazeTracker.position.x += deltaFighting;
  77749. }
  77750. else {
  77751. this._gazeTracker.position.x -= deltaFighting;
  77752. }
  77753. if (this._gazeTracker.position.y < 0) {
  77754. this._gazeTracker.position.y += deltaFighting;
  77755. }
  77756. else {
  77757. this._gazeTracker.position.y -= deltaFighting;
  77758. }
  77759. if (this._gazeTracker.position.z < 0) {
  77760. this._gazeTracker.position.z += deltaFighting;
  77761. }
  77762. else {
  77763. this._gazeTracker.position.z -= deltaFighting;
  77764. }
  77765. }
  77766. // Changing the size of the laser pointer based on the distance from the targetted point
  77767. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  77768. this._rightLaserPointer.scaling.y = hit.distance;
  77769. this._rightLaserPointer.position.z = -hit.distance / 2;
  77770. }
  77771. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  77772. this._leftLaserPointer.scaling.y = hit.distance;
  77773. this._leftLaserPointer.position.z = -hit.distance / 2;
  77774. }
  77775. }
  77776. else {
  77777. this._gazeTracker.isVisible = false;
  77778. }
  77779. if (hit && hit.pickedMesh) {
  77780. this._currentHit = hit;
  77781. if (this._pointerDownOnMeshAsked) {
  77782. this._scene.simulatePointerMove(this._currentHit);
  77783. }
  77784. // The object selected is the floor, we're in a teleportation scenario
  77785. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  77786. // Moving the teleportation area to this targetted point
  77787. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  77788. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  77789. this._notifySelectedMeshUnselected();
  77790. }
  77791. this._currentMeshSelected = null;
  77792. this._moveTeleportationSelectorTo(hit);
  77793. return;
  77794. }
  77795. // If not, we're in a selection scenario
  77796. this._hideTeleportationTarget();
  77797. this._teleportationAllowed = false;
  77798. if (hit.pickedMesh !== this._currentMeshSelected) {
  77799. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  77800. this.onNewMeshPicked.notifyObservers(hit);
  77801. this._currentMeshSelected = hit.pickedMesh;
  77802. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  77803. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  77804. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  77805. this._isActionableMesh = true;
  77806. }
  77807. else {
  77808. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77809. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77810. this._isActionableMesh = false;
  77811. }
  77812. try {
  77813. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  77814. }
  77815. catch (err) {
  77816. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  77817. }
  77818. }
  77819. else {
  77820. this._notifySelectedMeshUnselected();
  77821. this._currentMeshSelected = null;
  77822. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77823. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77824. }
  77825. }
  77826. }
  77827. else {
  77828. this._currentHit = null;
  77829. this._notifySelectedMeshUnselected();
  77830. this._currentMeshSelected = null;
  77831. this._teleportationAllowed = false;
  77832. this._hideTeleportationTarget();
  77833. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77834. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77835. }
  77836. };
  77837. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  77838. if (this._currentMeshSelected) {
  77839. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  77840. }
  77841. };
  77842. /**
  77843. * Sets the color of the laser ray from the vr controllers.
  77844. * @param color new color for the ray.
  77845. */
  77846. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  77847. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  77848. this._leftLaserPointer.material.emissiveColor = color;
  77849. }
  77850. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  77851. this._rightLaserPointer.material.emissiveColor = color;
  77852. }
  77853. };
  77854. /**
  77855. * Sets the color of the ray from the vr headsets gaze.
  77856. * @param color new color for the ray.
  77857. */
  77858. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  77859. if (this._gazeTracker.material) {
  77860. this._gazeTracker.material.emissiveColor = color;
  77861. }
  77862. };
  77863. /**
  77864. * Exits VR and disposes of the vr experience helper
  77865. */
  77866. VRExperienceHelper.prototype.dispose = function () {
  77867. if (this.isInVRMode) {
  77868. this.exitVR();
  77869. }
  77870. if (this._passProcessMove) {
  77871. this._passProcessMove.dispose();
  77872. }
  77873. if (this._postProcessMove) {
  77874. this._postProcessMove.dispose();
  77875. }
  77876. if (this._webVRCamera) {
  77877. this._webVRCamera.dispose();
  77878. }
  77879. if (this._vrDeviceOrientationCamera) {
  77880. this._vrDeviceOrientationCamera.dispose();
  77881. }
  77882. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  77883. document.body.removeChild(this._btnVR);
  77884. }
  77885. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  77886. this._deviceOrientationCamera.dispose();
  77887. }
  77888. if (this._gazeTracker) {
  77889. this._gazeTracker.dispose();
  77890. }
  77891. if (this._teleportationTarget) {
  77892. this._teleportationTarget.dispose();
  77893. }
  77894. this._floorMeshesCollection = [];
  77895. document.removeEventListener("keydown", this._onKeyDown);
  77896. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77897. window.removeEventListener("resize", this._onResize);
  77898. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  77899. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  77900. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  77901. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  77902. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  77903. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  77904. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  77905. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77906. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  77907. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  77908. this._scene.unregisterBeforeRender(this.beforeRender);
  77909. };
  77910. /**
  77911. * Gets the name of the VRExperienceHelper class
  77912. * @returns "VRExperienceHelper"
  77913. */
  77914. VRExperienceHelper.prototype.getClassName = function () {
  77915. return "VRExperienceHelper";
  77916. };
  77917. return VRExperienceHelper;
  77918. }());
  77919. BABYLON.VRExperienceHelper = VRExperienceHelper;
  77920. })(BABYLON || (BABYLON = {}));
  77921. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  77922. // Mainly based on these 2 articles :
  77923. // 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
  77924. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  77925. var BABYLON;
  77926. (function (BABYLON) {
  77927. var JoystickAxis;
  77928. (function (JoystickAxis) {
  77929. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  77930. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  77931. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  77932. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  77933. var VirtualJoystick = /** @class */ (function () {
  77934. function VirtualJoystick(leftJoystick) {
  77935. var _this = this;
  77936. if (leftJoystick) {
  77937. this._leftJoystick = true;
  77938. }
  77939. else {
  77940. this._leftJoystick = false;
  77941. }
  77942. VirtualJoystick._globalJoystickIndex++;
  77943. // By default left & right arrow keys are moving the X
  77944. // and up & down keys are moving the Y
  77945. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77946. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77947. this.reverseLeftRight = false;
  77948. this.reverseUpDown = false;
  77949. // collections of pointers
  77950. this._touches = new BABYLON.StringDictionary();
  77951. this.deltaPosition = BABYLON.Vector3.Zero();
  77952. this._joystickSensibility = 25;
  77953. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77954. this._onResize = function (evt) {
  77955. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77956. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77957. if (VirtualJoystick.vjCanvas) {
  77958. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  77959. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  77960. }
  77961. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  77962. };
  77963. // injecting a canvas element on top of the canvas 3D game
  77964. if (!VirtualJoystick.vjCanvas) {
  77965. window.addEventListener("resize", this._onResize, false);
  77966. VirtualJoystick.vjCanvas = document.createElement("canvas");
  77967. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77968. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77969. VirtualJoystick.vjCanvas.width = window.innerWidth;
  77970. VirtualJoystick.vjCanvas.height = window.innerHeight;
  77971. VirtualJoystick.vjCanvas.style.width = "100%";
  77972. VirtualJoystick.vjCanvas.style.height = "100%";
  77973. VirtualJoystick.vjCanvas.style.position = "absolute";
  77974. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  77975. VirtualJoystick.vjCanvas.style.top = "0px";
  77976. VirtualJoystick.vjCanvas.style.left = "0px";
  77977. VirtualJoystick.vjCanvas.style.zIndex = "5";
  77978. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  77979. // Support for jQuery PEP polyfill
  77980. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  77981. var context = VirtualJoystick.vjCanvas.getContext('2d');
  77982. if (!context) {
  77983. throw new Error("Unable to create canvas for virtual joystick");
  77984. }
  77985. VirtualJoystick.vjCanvasContext = context;
  77986. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  77987. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77988. document.body.appendChild(VirtualJoystick.vjCanvas);
  77989. }
  77990. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  77991. this.pressed = false;
  77992. // default joystick color
  77993. this._joystickColor = "cyan";
  77994. this._joystickPointerID = -1;
  77995. // current joystick position
  77996. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  77997. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  77998. // origin joystick position
  77999. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  78000. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  78001. this._onPointerDownHandlerRef = function (evt) {
  78002. _this._onPointerDown(evt);
  78003. };
  78004. this._onPointerMoveHandlerRef = function (evt) {
  78005. _this._onPointerMove(evt);
  78006. };
  78007. this._onPointerUpHandlerRef = function (evt) {
  78008. _this._onPointerUp(evt);
  78009. };
  78010. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  78011. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  78012. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  78013. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  78014. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  78015. evt.preventDefault(); // Disables system menu
  78016. }, false);
  78017. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78018. }
  78019. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  78020. this._joystickSensibility = newJoystickSensibility;
  78021. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  78022. };
  78023. VirtualJoystick.prototype._onPointerDown = function (e) {
  78024. var positionOnScreenCondition;
  78025. e.preventDefault();
  78026. if (this._leftJoystick === true) {
  78027. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  78028. }
  78029. else {
  78030. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  78031. }
  78032. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  78033. // First contact will be dedicated to the virtual joystick
  78034. this._joystickPointerID = e.pointerId;
  78035. this._joystickPointerStartPos.x = e.clientX;
  78036. this._joystickPointerStartPos.y = e.clientY;
  78037. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  78038. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  78039. this._deltaJoystickVector.x = 0;
  78040. this._deltaJoystickVector.y = 0;
  78041. this.pressed = true;
  78042. this._touches.add(e.pointerId.toString(), e);
  78043. }
  78044. else {
  78045. // You can only trigger the action buttons with a joystick declared
  78046. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  78047. this._action();
  78048. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  78049. }
  78050. }
  78051. };
  78052. VirtualJoystick.prototype._onPointerMove = function (e) {
  78053. // If the current pointer is the one associated to the joystick (first touch contact)
  78054. if (this._joystickPointerID == e.pointerId) {
  78055. this._joystickPointerPos.x = e.clientX;
  78056. this._joystickPointerPos.y = e.clientY;
  78057. this._deltaJoystickVector = this._joystickPointerPos.clone();
  78058. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  78059. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  78060. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  78061. switch (this._axisTargetedByLeftAndRight) {
  78062. case JoystickAxis.X:
  78063. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  78064. break;
  78065. case JoystickAxis.Y:
  78066. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  78067. break;
  78068. case JoystickAxis.Z:
  78069. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  78070. break;
  78071. }
  78072. var directionUpDown = this.reverseUpDown ? 1 : -1;
  78073. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  78074. switch (this._axisTargetedByUpAndDown) {
  78075. case JoystickAxis.X:
  78076. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  78077. break;
  78078. case JoystickAxis.Y:
  78079. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  78080. break;
  78081. case JoystickAxis.Z:
  78082. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  78083. break;
  78084. }
  78085. }
  78086. else {
  78087. var data = this._touches.get(e.pointerId.toString());
  78088. if (data) {
  78089. data.x = e.clientX;
  78090. data.y = e.clientY;
  78091. }
  78092. }
  78093. };
  78094. VirtualJoystick.prototype._onPointerUp = function (e) {
  78095. if (this._joystickPointerID == e.pointerId) {
  78096. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  78097. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  78098. this._joystickPointerID = -1;
  78099. this.pressed = false;
  78100. }
  78101. else {
  78102. var touch = this._touches.get(e.pointerId.toString());
  78103. if (touch) {
  78104. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78105. }
  78106. }
  78107. this._deltaJoystickVector.x = 0;
  78108. this._deltaJoystickVector.y = 0;
  78109. this._touches.remove(e.pointerId.toString());
  78110. };
  78111. /**
  78112. * Change the color of the virtual joystick
  78113. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  78114. */
  78115. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  78116. this._joystickColor = newColor;
  78117. };
  78118. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  78119. this._action = action;
  78120. };
  78121. // Define which axis you'd like to control for left & right
  78122. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  78123. switch (axis) {
  78124. case JoystickAxis.X:
  78125. case JoystickAxis.Y:
  78126. case JoystickAxis.Z:
  78127. this._axisTargetedByLeftAndRight = axis;
  78128. break;
  78129. default:
  78130. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  78131. break;
  78132. }
  78133. };
  78134. // Define which axis you'd like to control for up & down
  78135. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  78136. switch (axis) {
  78137. case JoystickAxis.X:
  78138. case JoystickAxis.Y:
  78139. case JoystickAxis.Z:
  78140. this._axisTargetedByUpAndDown = axis;
  78141. break;
  78142. default:
  78143. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  78144. break;
  78145. }
  78146. };
  78147. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  78148. var _this = this;
  78149. if (this.pressed) {
  78150. this._touches.forEach(function (key, touch) {
  78151. if (touch.pointerId === _this._joystickPointerID) {
  78152. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  78153. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  78154. VirtualJoystick.vjCanvasContext.beginPath();
  78155. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78156. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78157. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  78158. VirtualJoystick.vjCanvasContext.stroke();
  78159. VirtualJoystick.vjCanvasContext.closePath();
  78160. VirtualJoystick.vjCanvasContext.beginPath();
  78161. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78162. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  78163. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  78164. VirtualJoystick.vjCanvasContext.stroke();
  78165. VirtualJoystick.vjCanvasContext.closePath();
  78166. VirtualJoystick.vjCanvasContext.beginPath();
  78167. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78168. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  78169. VirtualJoystick.vjCanvasContext.stroke();
  78170. VirtualJoystick.vjCanvasContext.closePath();
  78171. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  78172. }
  78173. else {
  78174. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78175. VirtualJoystick.vjCanvasContext.beginPath();
  78176. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  78177. VirtualJoystick.vjCanvasContext.beginPath();
  78178. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  78179. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78180. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  78181. VirtualJoystick.vjCanvasContext.stroke();
  78182. VirtualJoystick.vjCanvasContext.closePath();
  78183. touch.prevX = touch.x;
  78184. touch.prevY = touch.y;
  78185. }
  78186. ;
  78187. });
  78188. }
  78189. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78190. };
  78191. VirtualJoystick.prototype.releaseCanvas = function () {
  78192. if (VirtualJoystick.vjCanvas) {
  78193. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  78194. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  78195. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  78196. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  78197. window.removeEventListener("resize", this._onResize);
  78198. document.body.removeChild(VirtualJoystick.vjCanvas);
  78199. VirtualJoystick.vjCanvas = null;
  78200. }
  78201. };
  78202. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  78203. VirtualJoystick._globalJoystickIndex = 0;
  78204. return VirtualJoystick;
  78205. }());
  78206. BABYLON.VirtualJoystick = VirtualJoystick;
  78207. })(BABYLON || (BABYLON = {}));
  78208. //# sourceMappingURL=babylon.virtualJoystick.js.map
  78209. var BABYLON;
  78210. (function (BABYLON) {
  78211. // We're mainly based on the logic defined into the FreeCamera code
  78212. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  78213. __extends(VirtualJoysticksCamera, _super);
  78214. function VirtualJoysticksCamera(name, position, scene) {
  78215. var _this = _super.call(this, name, position, scene) || this;
  78216. _this.inputs.addVirtualJoystick();
  78217. return _this;
  78218. }
  78219. VirtualJoysticksCamera.prototype.getClassName = function () {
  78220. return "VirtualJoysticksCamera";
  78221. };
  78222. return VirtualJoysticksCamera;
  78223. }(BABYLON.FreeCamera));
  78224. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  78225. })(BABYLON || (BABYLON = {}));
  78226. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  78227. var BABYLON;
  78228. (function (BABYLON) {
  78229. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  78230. function FreeCameraVirtualJoystickInput() {
  78231. }
  78232. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  78233. return this._leftjoystick;
  78234. };
  78235. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  78236. return this._rightjoystick;
  78237. };
  78238. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  78239. if (this._leftjoystick) {
  78240. var camera = this.camera;
  78241. var speed = camera._computeLocalCameraSpeed() * 50;
  78242. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  78243. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  78244. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  78245. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  78246. if (!this._leftjoystick.pressed) {
  78247. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  78248. }
  78249. if (!this._rightjoystick.pressed) {
  78250. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  78251. }
  78252. }
  78253. };
  78254. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  78255. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  78256. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  78257. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  78258. this._leftjoystick.setJoystickSensibility(0.15);
  78259. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  78260. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  78261. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  78262. this._rightjoystick.reverseUpDown = true;
  78263. this._rightjoystick.setJoystickSensibility(0.05);
  78264. this._rightjoystick.setJoystickColor("yellow");
  78265. };
  78266. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  78267. this._leftjoystick.releaseCanvas();
  78268. this._rightjoystick.releaseCanvas();
  78269. };
  78270. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  78271. return "FreeCameraVirtualJoystickInput";
  78272. };
  78273. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  78274. return "virtualJoystick";
  78275. };
  78276. return FreeCameraVirtualJoystickInput;
  78277. }());
  78278. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  78279. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  78280. })(BABYLON || (BABYLON = {}));
  78281. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  78282. var BABYLON;
  78283. (function (BABYLON) {
  78284. var SimplificationSettings = /** @class */ (function () {
  78285. function SimplificationSettings(quality, distance, optimizeMesh) {
  78286. this.quality = quality;
  78287. this.distance = distance;
  78288. this.optimizeMesh = optimizeMesh;
  78289. }
  78290. return SimplificationSettings;
  78291. }());
  78292. BABYLON.SimplificationSettings = SimplificationSettings;
  78293. var SimplificationQueue = /** @class */ (function () {
  78294. function SimplificationQueue() {
  78295. this.running = false;
  78296. this._simplificationArray = [];
  78297. }
  78298. SimplificationQueue.prototype.addTask = function (task) {
  78299. this._simplificationArray.push(task);
  78300. };
  78301. SimplificationQueue.prototype.executeNext = function () {
  78302. var task = this._simplificationArray.pop();
  78303. if (task) {
  78304. this.running = true;
  78305. this.runSimplification(task);
  78306. }
  78307. else {
  78308. this.running = false;
  78309. }
  78310. };
  78311. SimplificationQueue.prototype.runSimplification = function (task) {
  78312. var _this = this;
  78313. if (task.parallelProcessing) {
  78314. //parallel simplifier
  78315. task.settings.forEach(function (setting) {
  78316. var simplifier = _this.getSimplifier(task);
  78317. simplifier.simplify(setting, function (newMesh) {
  78318. task.mesh.addLODLevel(setting.distance, newMesh);
  78319. newMesh.isVisible = true;
  78320. //check if it is the last
  78321. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  78322. //all done, run the success callback.
  78323. task.successCallback();
  78324. }
  78325. _this.executeNext();
  78326. });
  78327. });
  78328. }
  78329. else {
  78330. //single simplifier.
  78331. var simplifier = this.getSimplifier(task);
  78332. var runDecimation = function (setting, callback) {
  78333. simplifier.simplify(setting, function (newMesh) {
  78334. task.mesh.addLODLevel(setting.distance, newMesh);
  78335. newMesh.isVisible = true;
  78336. //run the next quality level
  78337. callback();
  78338. });
  78339. };
  78340. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  78341. runDecimation(task.settings[loop.index], function () {
  78342. loop.executeNext();
  78343. });
  78344. }, function () {
  78345. //execution ended, run the success callback.
  78346. if (task.successCallback) {
  78347. task.successCallback();
  78348. }
  78349. _this.executeNext();
  78350. });
  78351. }
  78352. };
  78353. SimplificationQueue.prototype.getSimplifier = function (task) {
  78354. switch (task.simplificationType) {
  78355. case SimplificationType.QUADRATIC:
  78356. default:
  78357. return new QuadraticErrorSimplification(task.mesh);
  78358. }
  78359. };
  78360. return SimplificationQueue;
  78361. }());
  78362. BABYLON.SimplificationQueue = SimplificationQueue;
  78363. /**
  78364. * The implemented types of simplification.
  78365. * At the moment only Quadratic Error Decimation is implemented.
  78366. */
  78367. var SimplificationType;
  78368. (function (SimplificationType) {
  78369. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  78370. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  78371. var DecimationTriangle = /** @class */ (function () {
  78372. function DecimationTriangle(vertices) {
  78373. this.vertices = vertices;
  78374. this.error = new Array(4);
  78375. this.deleted = false;
  78376. this.isDirty = false;
  78377. this.deletePending = false;
  78378. this.borderFactor = 0;
  78379. }
  78380. return DecimationTriangle;
  78381. }());
  78382. BABYLON.DecimationTriangle = DecimationTriangle;
  78383. var DecimationVertex = /** @class */ (function () {
  78384. function DecimationVertex(position, id) {
  78385. this.position = position;
  78386. this.id = id;
  78387. this.isBorder = true;
  78388. this.q = new QuadraticMatrix();
  78389. this.triangleCount = 0;
  78390. this.triangleStart = 0;
  78391. this.originalOffsets = [];
  78392. }
  78393. DecimationVertex.prototype.updatePosition = function (newPosition) {
  78394. this.position.copyFrom(newPosition);
  78395. };
  78396. return DecimationVertex;
  78397. }());
  78398. BABYLON.DecimationVertex = DecimationVertex;
  78399. var QuadraticMatrix = /** @class */ (function () {
  78400. function QuadraticMatrix(data) {
  78401. this.data = new Array(10);
  78402. for (var i = 0; i < 10; ++i) {
  78403. if (data && data[i]) {
  78404. this.data[i] = data[i];
  78405. }
  78406. else {
  78407. this.data[i] = 0;
  78408. }
  78409. }
  78410. }
  78411. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  78412. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  78413. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  78414. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  78415. return det;
  78416. };
  78417. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  78418. for (var i = 0; i < 10; ++i) {
  78419. this.data[i] += matrix.data[i];
  78420. }
  78421. };
  78422. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  78423. for (var i = 0; i < 10; ++i) {
  78424. this.data[i] += data[i];
  78425. }
  78426. };
  78427. QuadraticMatrix.prototype.add = function (matrix) {
  78428. var m = new QuadraticMatrix();
  78429. for (var i = 0; i < 10; ++i) {
  78430. m.data[i] = this.data[i] + matrix.data[i];
  78431. }
  78432. return m;
  78433. };
  78434. QuadraticMatrix.FromData = function (a, b, c, d) {
  78435. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78436. };
  78437. //returning an array to avoid garbage collection
  78438. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  78439. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  78440. };
  78441. return QuadraticMatrix;
  78442. }());
  78443. BABYLON.QuadraticMatrix = QuadraticMatrix;
  78444. var Reference = /** @class */ (function () {
  78445. function Reference(vertexId, triangleId) {
  78446. this.vertexId = vertexId;
  78447. this.triangleId = triangleId;
  78448. }
  78449. return Reference;
  78450. }());
  78451. BABYLON.Reference = Reference;
  78452. /**
  78453. * An implementation of the Quadratic Error simplification algorithm.
  78454. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  78455. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  78456. * @author RaananW
  78457. */
  78458. var QuadraticErrorSimplification = /** @class */ (function () {
  78459. function QuadraticErrorSimplification(_mesh) {
  78460. this._mesh = _mesh;
  78461. this.syncIterations = 5000;
  78462. this.aggressiveness = 7;
  78463. this.decimationIterations = 100;
  78464. this.boundingBoxEpsilon = BABYLON.Epsilon;
  78465. }
  78466. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  78467. var _this = this;
  78468. this.initDecimatedMesh();
  78469. //iterating through the submeshes array, one after the other.
  78470. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  78471. _this.initWithMesh(loop.index, function () {
  78472. _this.runDecimation(settings, loop.index, function () {
  78473. loop.executeNext();
  78474. });
  78475. }, settings.optimizeMesh);
  78476. }, function () {
  78477. setTimeout(function () {
  78478. successCallback(_this._reconstructedMesh);
  78479. }, 0);
  78480. });
  78481. };
  78482. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  78483. var _this = this;
  78484. var targetCount = ~~(this.triangles.length * settings.quality);
  78485. var deletedTriangles = 0;
  78486. var triangleCount = this.triangles.length;
  78487. var iterationFunction = function (iteration, callback) {
  78488. setTimeout(function () {
  78489. if (iteration % 5 === 0) {
  78490. _this.updateMesh(iteration === 0);
  78491. }
  78492. for (var i = 0; i < _this.triangles.length; ++i) {
  78493. _this.triangles[i].isDirty = false;
  78494. }
  78495. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  78496. var trianglesIterator = function (i) {
  78497. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  78498. var t = _this.triangles[tIdx];
  78499. if (!t)
  78500. return;
  78501. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  78502. return;
  78503. }
  78504. for (var j = 0; j < 3; ++j) {
  78505. if (t.error[j] < threshold) {
  78506. var deleted0 = [];
  78507. var deleted1 = [];
  78508. var v0 = t.vertices[j];
  78509. var v1 = t.vertices[(j + 1) % 3];
  78510. if (v0.isBorder || v1.isBorder)
  78511. continue;
  78512. var p = BABYLON.Vector3.Zero();
  78513. var n = BABYLON.Vector3.Zero();
  78514. var uv = BABYLON.Vector2.Zero();
  78515. var color = new BABYLON.Color4(0, 0, 0, 1);
  78516. _this.calculateError(v0, v1, p, n, uv, color);
  78517. var delTr = new Array();
  78518. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  78519. continue;
  78520. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  78521. continue;
  78522. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  78523. continue;
  78524. var uniqueArray = new Array();
  78525. delTr.forEach(function (deletedT) {
  78526. if (uniqueArray.indexOf(deletedT) === -1) {
  78527. deletedT.deletePending = true;
  78528. uniqueArray.push(deletedT);
  78529. }
  78530. });
  78531. if (uniqueArray.length % 2 !== 0) {
  78532. continue;
  78533. }
  78534. v0.q = v1.q.add(v0.q);
  78535. v0.updatePosition(p);
  78536. var tStart = _this.references.length;
  78537. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  78538. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  78539. var tCount = _this.references.length - tStart;
  78540. if (tCount <= v0.triangleCount) {
  78541. if (tCount) {
  78542. for (var c = 0; c < tCount; c++) {
  78543. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  78544. }
  78545. }
  78546. }
  78547. else {
  78548. v0.triangleStart = tStart;
  78549. }
  78550. v0.triangleCount = tCount;
  78551. break;
  78552. }
  78553. }
  78554. };
  78555. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  78556. }, 0);
  78557. };
  78558. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  78559. if (triangleCount - deletedTriangles <= targetCount)
  78560. loop.breakLoop();
  78561. else {
  78562. iterationFunction(loop.index, function () {
  78563. loop.executeNext();
  78564. });
  78565. }
  78566. }, function () {
  78567. setTimeout(function () {
  78568. //reconstruct this part of the mesh
  78569. _this.reconstructMesh(submeshIndex);
  78570. successCallback();
  78571. }, 0);
  78572. });
  78573. };
  78574. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  78575. var _this = this;
  78576. this.vertices = [];
  78577. this.triangles = [];
  78578. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78579. var indices = this._mesh.getIndices();
  78580. var submesh = this._mesh.subMeshes[submeshIndex];
  78581. var findInVertices = function (positionToSearch) {
  78582. if (optimizeMesh) {
  78583. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  78584. if (_this.vertices[ii].position.equals(positionToSearch)) {
  78585. return _this.vertices[ii];
  78586. }
  78587. }
  78588. }
  78589. return null;
  78590. };
  78591. var vertexReferences = [];
  78592. var vertexInit = function (i) {
  78593. if (!positionData) {
  78594. return;
  78595. }
  78596. var offset = i + submesh.verticesStart;
  78597. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  78598. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  78599. vertex.originalOffsets.push(offset);
  78600. if (vertex.id === _this.vertices.length) {
  78601. _this.vertices.push(vertex);
  78602. }
  78603. vertexReferences.push(vertex.id);
  78604. };
  78605. //var totalVertices = mesh.getTotalVertices();
  78606. var totalVertices = submesh.verticesCount;
  78607. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  78608. var indicesInit = function (i) {
  78609. if (!indices) {
  78610. return;
  78611. }
  78612. var offset = (submesh.indexStart / 3) + i;
  78613. var pos = (offset * 3);
  78614. var i0 = indices[pos + 0];
  78615. var i1 = indices[pos + 1];
  78616. var i2 = indices[pos + 2];
  78617. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  78618. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  78619. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  78620. var triangle = new DecimationTriangle([v0, v1, v2]);
  78621. triangle.originalOffset = pos;
  78622. _this.triangles.push(triangle);
  78623. };
  78624. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  78625. _this.init(callback);
  78626. });
  78627. });
  78628. };
  78629. QuadraticErrorSimplification.prototype.init = function (callback) {
  78630. var _this = this;
  78631. var triangleInit1 = function (i) {
  78632. var t = _this.triangles[i];
  78633. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  78634. for (var j = 0; j < 3; j++) {
  78635. 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))));
  78636. }
  78637. };
  78638. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  78639. var triangleInit2 = function (i) {
  78640. var t = _this.triangles[i];
  78641. for (var j = 0; j < 3; ++j) {
  78642. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  78643. }
  78644. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78645. };
  78646. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  78647. callback();
  78648. });
  78649. });
  78650. };
  78651. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  78652. var newTriangles = [];
  78653. var i;
  78654. for (i = 0; i < this.vertices.length; ++i) {
  78655. this.vertices[i].triangleCount = 0;
  78656. }
  78657. var t;
  78658. var j;
  78659. for (i = 0; i < this.triangles.length; ++i) {
  78660. if (!this.triangles[i].deleted) {
  78661. t = this.triangles[i];
  78662. for (j = 0; j < 3; ++j) {
  78663. t.vertices[j].triangleCount = 1;
  78664. }
  78665. newTriangles.push(t);
  78666. }
  78667. }
  78668. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  78669. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  78670. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  78671. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  78672. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  78673. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78674. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  78675. var vertexCount = 0;
  78676. for (i = 0; i < this.vertices.length; ++i) {
  78677. var vertex = this.vertices[i];
  78678. vertex.id = vertexCount;
  78679. if (vertex.triangleCount) {
  78680. vertex.originalOffsets.forEach(function (originalOffset) {
  78681. if (!normalData) {
  78682. return;
  78683. }
  78684. newPositionData.push(vertex.position.x);
  78685. newPositionData.push(vertex.position.y);
  78686. newPositionData.push(vertex.position.z);
  78687. newNormalData.push(normalData[originalOffset * 3]);
  78688. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  78689. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  78690. if (uvs && uvs.length) {
  78691. newUVsData.push(uvs[(originalOffset * 2)]);
  78692. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  78693. }
  78694. else if (colorsData && colorsData.length) {
  78695. newColorsData.push(colorsData[(originalOffset * 4)]);
  78696. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  78697. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  78698. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  78699. }
  78700. ++vertexCount;
  78701. });
  78702. }
  78703. }
  78704. var startingIndex = this._reconstructedMesh.getTotalIndices();
  78705. var startingVertex = this._reconstructedMesh.getTotalVertices();
  78706. var submeshesArray = this._reconstructedMesh.subMeshes;
  78707. this._reconstructedMesh.subMeshes = [];
  78708. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  78709. var originalIndices = this._mesh.getIndices();
  78710. for (i = 0; i < newTriangles.length; ++i) {
  78711. t = newTriangles[i]; //now get the new referencing point for each vertex
  78712. [0, 1, 2].forEach(function (idx) {
  78713. var id = originalIndices[t.originalOffset + idx];
  78714. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  78715. if (offset < 0)
  78716. offset = 0;
  78717. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  78718. });
  78719. }
  78720. //overwriting the old vertex buffers and indices.
  78721. this._reconstructedMesh.setIndices(newIndicesArray);
  78722. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  78723. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  78724. if (newUVsData.length > 0)
  78725. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  78726. if (newColorsData.length > 0)
  78727. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  78728. //create submesh
  78729. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  78730. if (submeshIndex > 0) {
  78731. this._reconstructedMesh.subMeshes = [];
  78732. submeshesArray.forEach(function (submesh) {
  78733. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  78734. });
  78735. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  78736. }
  78737. };
  78738. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  78739. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  78740. this._reconstructedMesh.material = this._mesh.material;
  78741. this._reconstructedMesh.parent = this._mesh.parent;
  78742. this._reconstructedMesh.isVisible = false;
  78743. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  78744. };
  78745. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  78746. for (var i = 0; i < vertex1.triangleCount; ++i) {
  78747. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  78748. if (t.deleted)
  78749. continue;
  78750. var s = this.references[vertex1.triangleStart + i].vertexId;
  78751. var v1 = t.vertices[(s + 1) % 3];
  78752. var v2 = t.vertices[(s + 2) % 3];
  78753. if ((v1 === vertex2 || v2 === vertex2)) {
  78754. deletedArray[i] = true;
  78755. delTr.push(t);
  78756. continue;
  78757. }
  78758. var d1 = v1.position.subtract(point);
  78759. d1 = d1.normalize();
  78760. var d2 = v2.position.subtract(point);
  78761. d2 = d2.normalize();
  78762. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  78763. return true;
  78764. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  78765. deletedArray[i] = false;
  78766. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  78767. return true;
  78768. }
  78769. return false;
  78770. };
  78771. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  78772. var newDeleted = deletedTriangles;
  78773. for (var i = 0; i < vertex.triangleCount; ++i) {
  78774. var ref = this.references[vertex.triangleStart + i];
  78775. var t = this.triangles[ref.triangleId];
  78776. if (t.deleted)
  78777. continue;
  78778. if (deletedArray[i] && t.deletePending) {
  78779. t.deleted = true;
  78780. newDeleted++;
  78781. continue;
  78782. }
  78783. t.vertices[ref.vertexId] = origVertex;
  78784. t.isDirty = true;
  78785. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  78786. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  78787. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  78788. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78789. this.references.push(ref);
  78790. }
  78791. return newDeleted;
  78792. };
  78793. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  78794. for (var i = 0; i < this.vertices.length; ++i) {
  78795. var vCount = [];
  78796. var vId = [];
  78797. var v = this.vertices[i];
  78798. var j;
  78799. for (j = 0; j < v.triangleCount; ++j) {
  78800. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  78801. for (var ii = 0; ii < 3; ii++) {
  78802. var ofs = 0;
  78803. var vv = triangle.vertices[ii];
  78804. while (ofs < vCount.length) {
  78805. if (vId[ofs] === vv.id)
  78806. break;
  78807. ++ofs;
  78808. }
  78809. if (ofs === vCount.length) {
  78810. vCount.push(1);
  78811. vId.push(vv.id);
  78812. }
  78813. else {
  78814. vCount[ofs]++;
  78815. }
  78816. }
  78817. }
  78818. for (j = 0; j < vCount.length; ++j) {
  78819. if (vCount[j] === 1) {
  78820. this.vertices[vId[j]].isBorder = true;
  78821. }
  78822. else {
  78823. this.vertices[vId[j]].isBorder = false;
  78824. }
  78825. }
  78826. }
  78827. };
  78828. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  78829. if (identifyBorders === void 0) { identifyBorders = false; }
  78830. var i;
  78831. if (!identifyBorders) {
  78832. var newTrianglesVector = [];
  78833. for (i = 0; i < this.triangles.length; ++i) {
  78834. if (!this.triangles[i].deleted) {
  78835. newTrianglesVector.push(this.triangles[i]);
  78836. }
  78837. }
  78838. this.triangles = newTrianglesVector;
  78839. }
  78840. for (i = 0; i < this.vertices.length; ++i) {
  78841. this.vertices[i].triangleCount = 0;
  78842. this.vertices[i].triangleStart = 0;
  78843. }
  78844. var t;
  78845. var j;
  78846. var v;
  78847. for (i = 0; i < this.triangles.length; ++i) {
  78848. t = this.triangles[i];
  78849. for (j = 0; j < 3; ++j) {
  78850. v = t.vertices[j];
  78851. v.triangleCount++;
  78852. }
  78853. }
  78854. var tStart = 0;
  78855. for (i = 0; i < this.vertices.length; ++i) {
  78856. this.vertices[i].triangleStart = tStart;
  78857. tStart += this.vertices[i].triangleCount;
  78858. this.vertices[i].triangleCount = 0;
  78859. }
  78860. var newReferences = new Array(this.triangles.length * 3);
  78861. for (i = 0; i < this.triangles.length; ++i) {
  78862. t = this.triangles[i];
  78863. for (j = 0; j < 3; ++j) {
  78864. v = t.vertices[j];
  78865. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  78866. v.triangleCount++;
  78867. }
  78868. }
  78869. this.references = newReferences;
  78870. if (identifyBorders) {
  78871. this.identifyBorder();
  78872. }
  78873. };
  78874. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  78875. var x = point.x;
  78876. var y = point.y;
  78877. var z = point.z;
  78878. 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
  78879. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  78880. };
  78881. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  78882. var q = vertex1.q.add(vertex2.q);
  78883. var border = vertex1.isBorder && vertex2.isBorder;
  78884. var error = 0;
  78885. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  78886. if (qDet !== 0 && !border) {
  78887. if (!pointResult) {
  78888. pointResult = BABYLON.Vector3.Zero();
  78889. }
  78890. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  78891. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  78892. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  78893. error = this.vertexError(q, pointResult);
  78894. }
  78895. else {
  78896. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  78897. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  78898. var error1 = this.vertexError(q, vertex1.position);
  78899. var error2 = this.vertexError(q, vertex2.position);
  78900. var error3 = this.vertexError(q, p3);
  78901. error = Math.min(error1, error2, error3);
  78902. if (error === error1) {
  78903. if (pointResult) {
  78904. pointResult.copyFrom(vertex1.position);
  78905. }
  78906. }
  78907. else if (error === error2) {
  78908. if (pointResult) {
  78909. pointResult.copyFrom(vertex2.position);
  78910. }
  78911. }
  78912. else {
  78913. if (pointResult) {
  78914. pointResult.copyFrom(p3);
  78915. }
  78916. }
  78917. }
  78918. return error;
  78919. };
  78920. return QuadraticErrorSimplification;
  78921. }());
  78922. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  78923. })(BABYLON || (BABYLON = {}));
  78924. //# sourceMappingURL=babylon.meshSimplification.js.map
  78925. var BABYLON;
  78926. (function (BABYLON) {
  78927. var MeshLODLevel = /** @class */ (function () {
  78928. function MeshLODLevel(distance, mesh) {
  78929. this.distance = distance;
  78930. this.mesh = mesh;
  78931. }
  78932. return MeshLODLevel;
  78933. }());
  78934. BABYLON.MeshLODLevel = MeshLODLevel;
  78935. })(BABYLON || (BABYLON = {}));
  78936. //# sourceMappingURL=babylon.meshLODLevel.js.map
  78937. var BABYLON;
  78938. (function (BABYLON) {
  78939. /**
  78940. * Defines the root class used to create scene optimization to use with SceneOptimizer
  78941. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78942. */
  78943. var SceneOptimization = /** @class */ (function () {
  78944. /**
  78945. * Creates the SceneOptimization object
  78946. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78947. * @param desc defines the description associated with the optimization
  78948. */
  78949. function SceneOptimization(
  78950. /**
  78951. * Defines the priority of this optimization (0 by default which means first in the list)
  78952. */
  78953. priority) {
  78954. if (priority === void 0) { priority = 0; }
  78955. this.priority = priority;
  78956. }
  78957. /**
  78958. * Gets a string describing the action executed by the current optimization
  78959. * @returns description string
  78960. */
  78961. SceneOptimization.prototype.getDescription = function () {
  78962. return "";
  78963. };
  78964. /**
  78965. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78966. * @param scene defines the current scene where to apply this optimization
  78967. * @param optimizer defines the current optimizer
  78968. * @returns true if everything that can be done was applied
  78969. */
  78970. SceneOptimization.prototype.apply = function (scene, optimizer) {
  78971. return true;
  78972. };
  78973. ;
  78974. return SceneOptimization;
  78975. }());
  78976. BABYLON.SceneOptimization = SceneOptimization;
  78977. /**
  78978. * Defines an optimization used to reduce the size of render target textures
  78979. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78980. */
  78981. var TextureOptimization = /** @class */ (function (_super) {
  78982. __extends(TextureOptimization, _super);
  78983. /**
  78984. * Creates the TextureOptimization object
  78985. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78986. * @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
  78987. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78988. */
  78989. function TextureOptimization(
  78990. /**
  78991. * Defines the priority of this optimization (0 by default which means first in the list)
  78992. */
  78993. priority,
  78994. /**
  78995. * 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
  78996. */
  78997. maximumSize,
  78998. /**
  78999. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  79000. */
  79001. step) {
  79002. if (priority === void 0) { priority = 0; }
  79003. if (maximumSize === void 0) { maximumSize = 1024; }
  79004. if (step === void 0) { step = 0.5; }
  79005. var _this = _super.call(this, priority) || this;
  79006. _this.priority = priority;
  79007. _this.maximumSize = maximumSize;
  79008. _this.step = step;
  79009. return _this;
  79010. }
  79011. /**
  79012. * Gets a string describing the action executed by the current optimization
  79013. * @returns description string
  79014. */
  79015. TextureOptimization.prototype.getDescription = function () {
  79016. return "Reducing render target texture size to " + this.maximumSize;
  79017. };
  79018. /**
  79019. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79020. * @param scene defines the current scene where to apply this optimization
  79021. * @param optimizer defines the current optimizer
  79022. * @returns true if everything that can be done was applied
  79023. */
  79024. TextureOptimization.prototype.apply = function (scene, optimizer) {
  79025. var allDone = true;
  79026. for (var index = 0; index < scene.textures.length; index++) {
  79027. var texture = scene.textures[index];
  79028. if (!texture.canRescale || texture.getContext) {
  79029. continue;
  79030. }
  79031. var currentSize = texture.getSize();
  79032. var maxDimension = Math.max(currentSize.width, currentSize.height);
  79033. if (maxDimension > this.maximumSize) {
  79034. texture.scale(this.step);
  79035. allDone = false;
  79036. }
  79037. }
  79038. return allDone;
  79039. };
  79040. return TextureOptimization;
  79041. }(SceneOptimization));
  79042. BABYLON.TextureOptimization = TextureOptimization;
  79043. /**
  79044. * Defines an optimization used to increase or decrease the rendering resolution
  79045. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79046. */
  79047. var HardwareScalingOptimization = /** @class */ (function (_super) {
  79048. __extends(HardwareScalingOptimization, _super);
  79049. /**
  79050. * Creates the HardwareScalingOptimization object
  79051. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79052. * @param maximumScale defines the maximum scale to use (2 by default)
  79053. * @param step defines the step to use between two passes (0.5 by default)
  79054. */
  79055. function HardwareScalingOptimization(
  79056. /**
  79057. * Defines the priority of this optimization (0 by default which means first in the list)
  79058. */
  79059. priority,
  79060. /**
  79061. * Defines the maximum scale to use (2 by default)
  79062. */
  79063. maximumScale,
  79064. /**
  79065. * Defines the step to use between two passes (0.5 by default)
  79066. */
  79067. step) {
  79068. if (priority === void 0) { priority = 0; }
  79069. if (maximumScale === void 0) { maximumScale = 2; }
  79070. if (step === void 0) { step = 0.25; }
  79071. var _this = _super.call(this, priority) || this;
  79072. _this.priority = priority;
  79073. _this.maximumScale = maximumScale;
  79074. _this.step = step;
  79075. _this._currentScale = -1;
  79076. _this._directionOffset = 1;
  79077. return _this;
  79078. }
  79079. /**
  79080. * Gets a string describing the action executed by the current optimization
  79081. * @return description string
  79082. */
  79083. HardwareScalingOptimization.prototype.getDescription = function () {
  79084. return "Setting hardware scaling level to " + this._currentScale;
  79085. };
  79086. /**
  79087. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79088. * @param scene defines the current scene where to apply this optimization
  79089. * @param optimizer defines the current optimizer
  79090. * @returns true if everything that can be done was applied
  79091. */
  79092. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  79093. if (this._currentScale === -1) {
  79094. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  79095. if (this._currentScale > this.maximumScale) {
  79096. this._directionOffset = -1;
  79097. }
  79098. }
  79099. this._currentScale += this._directionOffset * this.step;
  79100. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  79101. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  79102. };
  79103. ;
  79104. return HardwareScalingOptimization;
  79105. }(SceneOptimization));
  79106. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  79107. /**
  79108. * Defines an optimization used to remove shadows
  79109. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79110. */
  79111. var ShadowsOptimization = /** @class */ (function (_super) {
  79112. __extends(ShadowsOptimization, _super);
  79113. function ShadowsOptimization() {
  79114. return _super !== null && _super.apply(this, arguments) || this;
  79115. }
  79116. /**
  79117. * Gets a string describing the action executed by the current optimization
  79118. * @return description string
  79119. */
  79120. ShadowsOptimization.prototype.getDescription = function () {
  79121. return "Turning shadows on/off";
  79122. };
  79123. /**
  79124. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79125. * @param scene defines the current scene where to apply this optimization
  79126. * @param optimizer defines the current optimizer
  79127. * @returns true if everything that can be done was applied
  79128. */
  79129. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  79130. scene.shadowsEnabled = optimizer.isInImprovementMode;
  79131. return true;
  79132. };
  79133. ;
  79134. return ShadowsOptimization;
  79135. }(SceneOptimization));
  79136. BABYLON.ShadowsOptimization = ShadowsOptimization;
  79137. /**
  79138. * Defines an optimization used to turn post-processes off
  79139. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79140. */
  79141. var PostProcessesOptimization = /** @class */ (function (_super) {
  79142. __extends(PostProcessesOptimization, _super);
  79143. function PostProcessesOptimization() {
  79144. return _super !== null && _super.apply(this, arguments) || this;
  79145. }
  79146. /**
  79147. * Gets a string describing the action executed by the current optimization
  79148. * @return description string
  79149. */
  79150. PostProcessesOptimization.prototype.getDescription = function () {
  79151. return "Turning post-processes on/off";
  79152. };
  79153. /**
  79154. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79155. * @param scene defines the current scene where to apply this optimization
  79156. * @param optimizer defines the current optimizer
  79157. * @returns true if everything that can be done was applied
  79158. */
  79159. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  79160. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  79161. return true;
  79162. };
  79163. ;
  79164. return PostProcessesOptimization;
  79165. }(SceneOptimization));
  79166. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  79167. /**
  79168. * Defines an optimization used to turn lens flares off
  79169. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79170. */
  79171. var LensFlaresOptimization = /** @class */ (function (_super) {
  79172. __extends(LensFlaresOptimization, _super);
  79173. function LensFlaresOptimization() {
  79174. return _super !== null && _super.apply(this, arguments) || this;
  79175. }
  79176. /**
  79177. * Gets a string describing the action executed by the current optimization
  79178. * @return description string
  79179. */
  79180. LensFlaresOptimization.prototype.getDescription = function () {
  79181. return "Turning lens flares on/off";
  79182. };
  79183. /**
  79184. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79185. * @param scene defines the current scene where to apply this optimization
  79186. * @param optimizer defines the current optimizer
  79187. * @returns true if everything that can be done was applied
  79188. */
  79189. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  79190. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  79191. return true;
  79192. };
  79193. ;
  79194. return LensFlaresOptimization;
  79195. }(SceneOptimization));
  79196. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  79197. /**
  79198. * Defines an optimization based on user defined callback.
  79199. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79200. */
  79201. var CustomOptimization = /** @class */ (function (_super) {
  79202. __extends(CustomOptimization, _super);
  79203. function CustomOptimization() {
  79204. return _super !== null && _super.apply(this, arguments) || this;
  79205. }
  79206. /**
  79207. * Gets a string describing the action executed by the current optimization
  79208. * @returns description string
  79209. */
  79210. CustomOptimization.prototype.getDescription = function () {
  79211. if (this.onGetDescription) {
  79212. return this.onGetDescription();
  79213. }
  79214. return "Running user defined callback";
  79215. };
  79216. /**
  79217. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79218. * @param scene defines the current scene where to apply this optimization
  79219. * @param optimizer defines the current optimizer
  79220. * @returns true if everything that can be done was applied
  79221. */
  79222. CustomOptimization.prototype.apply = function (scene, optimizer) {
  79223. if (this.onApply) {
  79224. return this.onApply(scene, optimizer);
  79225. }
  79226. return true;
  79227. };
  79228. ;
  79229. return CustomOptimization;
  79230. }(SceneOptimization));
  79231. BABYLON.CustomOptimization = CustomOptimization;
  79232. /**
  79233. * Defines an optimization used to turn particles off
  79234. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79235. */
  79236. var ParticlesOptimization = /** @class */ (function (_super) {
  79237. __extends(ParticlesOptimization, _super);
  79238. function ParticlesOptimization() {
  79239. return _super !== null && _super.apply(this, arguments) || this;
  79240. }
  79241. /**
  79242. * Gets a string describing the action executed by the current optimization
  79243. * @return description string
  79244. */
  79245. ParticlesOptimization.prototype.getDescription = function () {
  79246. return "Turning particles on/off";
  79247. };
  79248. /**
  79249. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79250. * @param scene defines the current scene where to apply this optimization
  79251. * @param optimizer defines the current optimizer
  79252. * @returns true if everything that can be done was applied
  79253. */
  79254. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  79255. scene.particlesEnabled = optimizer.isInImprovementMode;
  79256. return true;
  79257. };
  79258. ;
  79259. return ParticlesOptimization;
  79260. }(SceneOptimization));
  79261. BABYLON.ParticlesOptimization = ParticlesOptimization;
  79262. /**
  79263. * Defines an optimization used to turn render targets off
  79264. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79265. */
  79266. var RenderTargetsOptimization = /** @class */ (function (_super) {
  79267. __extends(RenderTargetsOptimization, _super);
  79268. function RenderTargetsOptimization() {
  79269. return _super !== null && _super.apply(this, arguments) || this;
  79270. }
  79271. /**
  79272. * Gets a string describing the action executed by the current optimization
  79273. * @return description string
  79274. */
  79275. RenderTargetsOptimization.prototype.getDescription = function () {
  79276. return "Turning render targets off";
  79277. };
  79278. /**
  79279. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79280. * @param scene defines the current scene where to apply this optimization
  79281. * @param optimizer defines the current optimizer
  79282. * @returns true if everything that can be done was applied
  79283. */
  79284. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  79285. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  79286. return true;
  79287. };
  79288. ;
  79289. return RenderTargetsOptimization;
  79290. }(SceneOptimization));
  79291. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  79292. /**
  79293. * Defines an optimization used to merge meshes with compatible materials
  79294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79295. */
  79296. var MergeMeshesOptimization = /** @class */ (function (_super) {
  79297. __extends(MergeMeshesOptimization, _super);
  79298. function MergeMeshesOptimization() {
  79299. var _this = _super !== null && _super.apply(this, arguments) || this;
  79300. _this._canBeMerged = function (abstractMesh) {
  79301. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  79302. return false;
  79303. }
  79304. var mesh = abstractMesh;
  79305. if (!mesh.isVisible || !mesh.isEnabled()) {
  79306. return false;
  79307. }
  79308. if (mesh.instances.length > 0) {
  79309. return false;
  79310. }
  79311. if (mesh.skeleton || mesh.hasLODLevels) {
  79312. return false;
  79313. }
  79314. if (mesh.parent) {
  79315. return false;
  79316. }
  79317. return true;
  79318. };
  79319. return _this;
  79320. }
  79321. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  79322. /**
  79323. * Gets or sets a boolean which defines if optimization octree has to be updated
  79324. */
  79325. get: function () {
  79326. return MergeMeshesOptimization._UpdateSelectionTree;
  79327. },
  79328. /**
  79329. * Gets or sets a boolean which defines if optimization octree has to be updated
  79330. */
  79331. set: function (value) {
  79332. MergeMeshesOptimization._UpdateSelectionTree = value;
  79333. },
  79334. enumerable: true,
  79335. configurable: true
  79336. });
  79337. /**
  79338. * Gets a string describing the action executed by the current optimization
  79339. * @return description string
  79340. */
  79341. MergeMeshesOptimization.prototype.getDescription = function () {
  79342. return "Merging similar meshes together";
  79343. };
  79344. /**
  79345. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79346. * @param scene defines the current scene where to apply this optimization
  79347. * @param optimizer defines the current optimizer
  79348. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  79349. * @returns true if everything that can be done was applied
  79350. */
  79351. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  79352. var globalPool = scene.meshes.slice(0);
  79353. var globalLength = globalPool.length;
  79354. for (var index = 0; index < globalLength; index++) {
  79355. var currentPool = new Array();
  79356. var current = globalPool[index];
  79357. // Checks
  79358. if (!this._canBeMerged(current)) {
  79359. continue;
  79360. }
  79361. currentPool.push(current);
  79362. // Find compatible meshes
  79363. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  79364. var otherMesh = globalPool[subIndex];
  79365. if (!this._canBeMerged(otherMesh)) {
  79366. continue;
  79367. }
  79368. if (otherMesh.material !== current.material) {
  79369. continue;
  79370. }
  79371. if (otherMesh.checkCollisions !== current.checkCollisions) {
  79372. continue;
  79373. }
  79374. currentPool.push(otherMesh);
  79375. globalLength--;
  79376. globalPool.splice(subIndex, 1);
  79377. subIndex--;
  79378. }
  79379. if (currentPool.length < 2) {
  79380. continue;
  79381. }
  79382. // Merge meshes
  79383. BABYLON.Mesh.MergeMeshes(currentPool);
  79384. }
  79385. if (updateSelectionTree != undefined) {
  79386. if (updateSelectionTree) {
  79387. scene.createOrUpdateSelectionOctree();
  79388. }
  79389. }
  79390. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  79391. scene.createOrUpdateSelectionOctree();
  79392. }
  79393. return true;
  79394. };
  79395. ;
  79396. MergeMeshesOptimization._UpdateSelectionTree = false;
  79397. return MergeMeshesOptimization;
  79398. }(SceneOptimization));
  79399. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  79400. /**
  79401. * Defines a list of options used by SceneOptimizer
  79402. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79403. */
  79404. var SceneOptimizerOptions = /** @class */ (function () {
  79405. /**
  79406. * Creates a new list of options used by SceneOptimizer
  79407. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  79408. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  79409. */
  79410. function SceneOptimizerOptions(
  79411. /**
  79412. * Defines the target frame rate to reach (60 by default)
  79413. */
  79414. targetFrameRate,
  79415. /**
  79416. * Defines the interval between two checkes (2000ms by default)
  79417. */
  79418. trackerDuration) {
  79419. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  79420. if (trackerDuration === void 0) { trackerDuration = 2000; }
  79421. this.targetFrameRate = targetFrameRate;
  79422. this.trackerDuration = trackerDuration;
  79423. /**
  79424. * Gets the list of optimizations to apply
  79425. */
  79426. this.optimizations = new Array();
  79427. }
  79428. /**
  79429. * Add a new optimization
  79430. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  79431. * @returns the current SceneOptimizerOptions
  79432. */
  79433. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  79434. this.optimizations.push(optimization);
  79435. return this;
  79436. };
  79437. /**
  79438. * Add a new custom optimization
  79439. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  79440. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  79441. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79442. * @returns the current SceneOptimizerOptions
  79443. */
  79444. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  79445. if (priority === void 0) { priority = 0; }
  79446. var optimization = new CustomOptimization(priority);
  79447. optimization.onApply = onApply;
  79448. optimization.onGetDescription = onGetDescription;
  79449. this.optimizations.push(optimization);
  79450. return this;
  79451. };
  79452. /**
  79453. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  79454. * @param targetFrameRate defines the target frame rate (60 by default)
  79455. * @returns a SceneOptimizerOptions object
  79456. */
  79457. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  79458. var result = new SceneOptimizerOptions(targetFrameRate);
  79459. var priority = 0;
  79460. result.addOptimization(new MergeMeshesOptimization(priority));
  79461. result.addOptimization(new ShadowsOptimization(priority));
  79462. result.addOptimization(new LensFlaresOptimization(priority));
  79463. // Next priority
  79464. priority++;
  79465. result.addOptimization(new PostProcessesOptimization(priority));
  79466. result.addOptimization(new ParticlesOptimization(priority));
  79467. // Next priority
  79468. priority++;
  79469. result.addOptimization(new TextureOptimization(priority, 1024));
  79470. return result;
  79471. };
  79472. /**
  79473. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  79474. * @param targetFrameRate defines the target frame rate (60 by default)
  79475. * @returns a SceneOptimizerOptions object
  79476. */
  79477. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  79478. var result = new SceneOptimizerOptions(targetFrameRate);
  79479. var priority = 0;
  79480. result.addOptimization(new MergeMeshesOptimization(priority));
  79481. result.addOptimization(new ShadowsOptimization(priority));
  79482. result.addOptimization(new LensFlaresOptimization(priority));
  79483. // Next priority
  79484. priority++;
  79485. result.addOptimization(new PostProcessesOptimization(priority));
  79486. result.addOptimization(new ParticlesOptimization(priority));
  79487. // Next priority
  79488. priority++;
  79489. result.addOptimization(new TextureOptimization(priority, 512));
  79490. // Next priority
  79491. priority++;
  79492. result.addOptimization(new RenderTargetsOptimization(priority));
  79493. // Next priority
  79494. priority++;
  79495. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  79496. return result;
  79497. };
  79498. /**
  79499. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  79500. * @param targetFrameRate defines the target frame rate (60 by default)
  79501. * @returns a SceneOptimizerOptions object
  79502. */
  79503. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  79504. var result = new SceneOptimizerOptions(targetFrameRate);
  79505. var priority = 0;
  79506. result.addOptimization(new MergeMeshesOptimization(priority));
  79507. result.addOptimization(new ShadowsOptimization(priority));
  79508. result.addOptimization(new LensFlaresOptimization(priority));
  79509. // Next priority
  79510. priority++;
  79511. result.addOptimization(new PostProcessesOptimization(priority));
  79512. result.addOptimization(new ParticlesOptimization(priority));
  79513. // Next priority
  79514. priority++;
  79515. result.addOptimization(new TextureOptimization(priority, 256));
  79516. // Next priority
  79517. priority++;
  79518. result.addOptimization(new RenderTargetsOptimization(priority));
  79519. // Next priority
  79520. priority++;
  79521. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  79522. return result;
  79523. };
  79524. return SceneOptimizerOptions;
  79525. }());
  79526. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  79527. /**
  79528. * Class used to run optimizations in order to reach a target frame rate
  79529. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79530. */
  79531. var SceneOptimizer = /** @class */ (function () {
  79532. /**
  79533. * Creates a new SceneOptimizer
  79534. * @param scene defines the scene to work on
  79535. * @param options defines the options to use with the SceneOptimizer
  79536. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  79537. * @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)
  79538. */
  79539. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  79540. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  79541. if (improvementMode === void 0) { improvementMode = false; }
  79542. var _this = this;
  79543. this._isRunning = false;
  79544. this._currentPriorityLevel = 0;
  79545. this._targetFrameRate = 60;
  79546. this._trackerDuration = 2000;
  79547. this._currentFrameRate = 0;
  79548. this._improvementMode = false;
  79549. /**
  79550. * Defines an observable called when the optimizer reaches the target frame rate
  79551. */
  79552. this.onSuccessObservable = new BABYLON.Observable();
  79553. /**
  79554. * Defines an observable called when the optimizer enables an optimization
  79555. */
  79556. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  79557. /**
  79558. * Defines an observable called when the optimizer is not able to reach the target frame rate
  79559. */
  79560. this.onFailureObservable = new BABYLON.Observable();
  79561. if (!options) {
  79562. this._options = new SceneOptimizerOptions();
  79563. }
  79564. else {
  79565. this._options = options;
  79566. }
  79567. if (this._options.targetFrameRate) {
  79568. this._targetFrameRate = this._options.targetFrameRate;
  79569. }
  79570. if (this._options.trackerDuration) {
  79571. this._trackerDuration = this._options.trackerDuration;
  79572. }
  79573. if (autoGeneratePriorities) {
  79574. var priority = 0;
  79575. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  79576. var optim = _a[_i];
  79577. optim.priority = priority++;
  79578. }
  79579. }
  79580. this._improvementMode = improvementMode;
  79581. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79582. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  79583. _this._sceneDisposeObserver = null;
  79584. _this.dispose();
  79585. });
  79586. }
  79587. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  79588. /**
  79589. * Gets a boolean indicating if the optimizer is in improvement mode
  79590. */
  79591. get: function () {
  79592. return this._improvementMode;
  79593. },
  79594. enumerable: true,
  79595. configurable: true
  79596. });
  79597. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  79598. /**
  79599. * Gets the current priority level (0 at start)
  79600. */
  79601. get: function () {
  79602. return this._currentPriorityLevel;
  79603. },
  79604. enumerable: true,
  79605. configurable: true
  79606. });
  79607. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  79608. /**
  79609. * Gets the current frame rate checked by the SceneOptimizer
  79610. */
  79611. get: function () {
  79612. return this._currentFrameRate;
  79613. },
  79614. enumerable: true,
  79615. configurable: true
  79616. });
  79617. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  79618. /**
  79619. * Gets or sets the current target frame rate (60 by default)
  79620. */
  79621. get: function () {
  79622. return this._targetFrameRate;
  79623. },
  79624. /**
  79625. * Gets or sets the current target frame rate (60 by default)
  79626. */
  79627. set: function (value) {
  79628. this._targetFrameRate = value;
  79629. },
  79630. enumerable: true,
  79631. configurable: true
  79632. });
  79633. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  79634. /**
  79635. * Gets or sets the current interval between two checks (every 2000ms by default)
  79636. */
  79637. get: function () {
  79638. return this._trackerDuration;
  79639. },
  79640. /**
  79641. * Gets or sets the current interval between two checks (every 2000ms by default)
  79642. */
  79643. set: function (value) {
  79644. this._trackerDuration = value;
  79645. },
  79646. enumerable: true,
  79647. configurable: true
  79648. });
  79649. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  79650. /**
  79651. * Gets the list of active optimizations
  79652. */
  79653. get: function () {
  79654. return this._options.optimizations;
  79655. },
  79656. enumerable: true,
  79657. configurable: true
  79658. });
  79659. /**
  79660. * Stops the current optimizer
  79661. */
  79662. SceneOptimizer.prototype.stop = function () {
  79663. this._isRunning = false;
  79664. };
  79665. /**
  79666. * Reset the optimizer to initial step (current priority level = 0)
  79667. */
  79668. SceneOptimizer.prototype.reset = function () {
  79669. this._currentPriorityLevel = 0;
  79670. };
  79671. /**
  79672. * Start the optimizer. By default it will try to reach a specific framerate
  79673. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  79674. */
  79675. SceneOptimizer.prototype.start = function () {
  79676. var _this = this;
  79677. if (this._isRunning) {
  79678. return;
  79679. }
  79680. this._isRunning = true;
  79681. // Let's wait for the scene to be ready before running our check
  79682. this._scene.executeWhenReady(function () {
  79683. setTimeout(function () {
  79684. _this._checkCurrentState();
  79685. }, _this._trackerDuration);
  79686. });
  79687. };
  79688. SceneOptimizer.prototype._checkCurrentState = function () {
  79689. var _this = this;
  79690. if (!this._isRunning) {
  79691. return;
  79692. }
  79693. var scene = this._scene;
  79694. var options = this._options;
  79695. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  79696. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  79697. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  79698. this._isRunning = false;
  79699. this.onSuccessObservable.notifyObservers(this);
  79700. return;
  79701. }
  79702. // Apply current level of optimizations
  79703. var allDone = true;
  79704. var noOptimizationApplied = true;
  79705. for (var index = 0; index < options.optimizations.length; index++) {
  79706. var optimization = options.optimizations[index];
  79707. if (optimization.priority === this._currentPriorityLevel) {
  79708. noOptimizationApplied = false;
  79709. allDone = allDone && optimization.apply(scene, this);
  79710. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  79711. }
  79712. }
  79713. // If no optimization was applied, this is a failure :(
  79714. if (noOptimizationApplied) {
  79715. this._isRunning = false;
  79716. this.onFailureObservable.notifyObservers(this);
  79717. return;
  79718. }
  79719. // If all optimizations were done, move to next level
  79720. if (allDone) {
  79721. this._currentPriorityLevel++;
  79722. }
  79723. // Let's the system running for a specific amount of time before checking FPS
  79724. scene.executeWhenReady(function () {
  79725. setTimeout(function () {
  79726. _this._checkCurrentState();
  79727. }, _this._trackerDuration);
  79728. });
  79729. };
  79730. /**
  79731. * Release all resources
  79732. */
  79733. SceneOptimizer.prototype.dispose = function () {
  79734. this.stop();
  79735. this.onSuccessObservable.clear();
  79736. this.onFailureObservable.clear();
  79737. this.onNewOptimizationAppliedObservable.clear();
  79738. if (this._sceneDisposeObserver) {
  79739. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  79740. }
  79741. };
  79742. /**
  79743. * Helper function to create a SceneOptimizer with one single line of code
  79744. * @param scene defines the scene to work on
  79745. * @param options defines the options to use with the SceneOptimizer
  79746. * @param onSuccess defines a callback to call on success
  79747. * @param onFailure defines a callback to call on failure
  79748. * @returns the new SceneOptimizer object
  79749. */
  79750. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  79751. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  79752. if (onSuccess) {
  79753. optimizer.onSuccessObservable.add(function () {
  79754. onSuccess();
  79755. });
  79756. }
  79757. if (onFailure) {
  79758. optimizer.onFailureObservable.add(function () {
  79759. onFailure();
  79760. });
  79761. }
  79762. optimizer.start();
  79763. return optimizer;
  79764. };
  79765. return SceneOptimizer;
  79766. }());
  79767. BABYLON.SceneOptimizer = SceneOptimizer;
  79768. })(BABYLON || (BABYLON = {}));
  79769. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  79770. var BABYLON;
  79771. (function (BABYLON) {
  79772. var OutlineRenderer = /** @class */ (function () {
  79773. function OutlineRenderer(scene) {
  79774. this.zOffset = 1;
  79775. this._scene = scene;
  79776. }
  79777. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  79778. var _this = this;
  79779. if (useOverlay === void 0) { useOverlay = false; }
  79780. var scene = this._scene;
  79781. var engine = this._scene.getEngine();
  79782. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79783. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  79784. return;
  79785. }
  79786. var mesh = subMesh.getRenderingMesh();
  79787. var material = subMesh.getMaterial();
  79788. if (!material || !scene.activeCamera) {
  79789. return;
  79790. }
  79791. engine.enableEffect(this._effect);
  79792. // Logarithmic depth
  79793. if (material.useLogarithmicDepth) {
  79794. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  79795. }
  79796. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  79797. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  79798. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79799. // Bones
  79800. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79801. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79802. }
  79803. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  79804. // Alpha test
  79805. if (material && material.needAlphaTesting()) {
  79806. var alphaTexture = material.getAlphaTestTexture();
  79807. if (alphaTexture) {
  79808. this._effect.setTexture("diffuseSampler", alphaTexture);
  79809. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79810. }
  79811. }
  79812. engine.setZOffset(-this.zOffset);
  79813. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  79814. engine.setZOffset(0);
  79815. };
  79816. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  79817. var defines = [];
  79818. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79819. var mesh = subMesh.getMesh();
  79820. var material = subMesh.getMaterial();
  79821. if (material) {
  79822. // Alpha test
  79823. if (material.needAlphaTesting()) {
  79824. defines.push("#define ALPHATEST");
  79825. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79826. attribs.push(BABYLON.VertexBuffer.UVKind);
  79827. defines.push("#define UV1");
  79828. }
  79829. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79830. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79831. defines.push("#define UV2");
  79832. }
  79833. }
  79834. //Logarithmic depth
  79835. if (material.useLogarithmicDepth) {
  79836. defines.push("#define LOGARITHMICDEPTH");
  79837. }
  79838. }
  79839. // Bones
  79840. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79841. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79842. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79843. if (mesh.numBoneInfluencers > 4) {
  79844. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79845. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79846. }
  79847. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79848. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79849. }
  79850. else {
  79851. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79852. }
  79853. // Instances
  79854. if (useInstances) {
  79855. defines.push("#define INSTANCES");
  79856. attribs.push("world0");
  79857. attribs.push("world1");
  79858. attribs.push("world2");
  79859. attribs.push("world3");
  79860. }
  79861. // Get correct effect
  79862. var join = defines.join("\n");
  79863. if (this._cachedDefines !== join) {
  79864. this._cachedDefines = join;
  79865. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  79866. }
  79867. return this._effect.isReady();
  79868. };
  79869. return OutlineRenderer;
  79870. }());
  79871. BABYLON.OutlineRenderer = OutlineRenderer;
  79872. })(BABYLON || (BABYLON = {}));
  79873. //# sourceMappingURL=babylon.outlineRenderer.js.map
  79874. var BABYLON;
  79875. (function (BABYLON) {
  79876. var FaceAdjacencies = /** @class */ (function () {
  79877. function FaceAdjacencies() {
  79878. this.edges = new Array();
  79879. this.edgesConnectedCount = 0;
  79880. }
  79881. return FaceAdjacencies;
  79882. }());
  79883. var EdgesRenderer = /** @class */ (function () {
  79884. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  79885. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  79886. if (epsilon === void 0) { epsilon = 0.95; }
  79887. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  79888. this.edgesWidthScalerForOrthographic = 1000.0;
  79889. this.edgesWidthScalerForPerspective = 50.0;
  79890. this._linesPositions = new Array();
  79891. this._linesNormals = new Array();
  79892. this._linesIndices = new Array();
  79893. this._buffers = {};
  79894. this._checkVerticesInsteadOfIndices = false;
  79895. this._source = source;
  79896. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  79897. this._epsilon = epsilon;
  79898. this._prepareRessources();
  79899. this._generateEdgesLines();
  79900. }
  79901. EdgesRenderer.prototype._prepareRessources = function () {
  79902. if (this._lineShader) {
  79903. return;
  79904. }
  79905. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  79906. attributes: ["position", "normal"],
  79907. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  79908. });
  79909. this._lineShader.disableDepthWrite = true;
  79910. this._lineShader.backFaceCulling = false;
  79911. };
  79912. EdgesRenderer.prototype._rebuild = function () {
  79913. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79914. if (buffer) {
  79915. buffer._rebuild();
  79916. }
  79917. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79918. if (buffer) {
  79919. buffer._rebuild();
  79920. }
  79921. var scene = this._source.getScene();
  79922. var engine = scene.getEngine();
  79923. this._ib = engine.createIndexBuffer(this._linesIndices);
  79924. };
  79925. EdgesRenderer.prototype.dispose = function () {
  79926. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79927. if (buffer) {
  79928. buffer.dispose();
  79929. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  79930. }
  79931. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79932. if (buffer) {
  79933. buffer.dispose();
  79934. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  79935. }
  79936. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  79937. this._lineShader.dispose();
  79938. };
  79939. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  79940. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  79941. return 0;
  79942. }
  79943. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  79944. return 1;
  79945. }
  79946. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  79947. return 2;
  79948. }
  79949. return -1;
  79950. };
  79951. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  79952. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  79953. return 0;
  79954. }
  79955. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  79956. return 1;
  79957. }
  79958. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  79959. return 2;
  79960. }
  79961. return -1;
  79962. };
  79963. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  79964. var needToCreateLine;
  79965. if (edge === undefined) {
  79966. needToCreateLine = true;
  79967. }
  79968. else {
  79969. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  79970. needToCreateLine = dotProduct < this._epsilon;
  79971. }
  79972. if (needToCreateLine) {
  79973. var offset = this._linesPositions.length / 3;
  79974. var normal = p0.subtract(p1);
  79975. normal.normalize();
  79976. // Positions
  79977. this._linesPositions.push(p0.x);
  79978. this._linesPositions.push(p0.y);
  79979. this._linesPositions.push(p0.z);
  79980. this._linesPositions.push(p0.x);
  79981. this._linesPositions.push(p0.y);
  79982. this._linesPositions.push(p0.z);
  79983. this._linesPositions.push(p1.x);
  79984. this._linesPositions.push(p1.y);
  79985. this._linesPositions.push(p1.z);
  79986. this._linesPositions.push(p1.x);
  79987. this._linesPositions.push(p1.y);
  79988. this._linesPositions.push(p1.z);
  79989. // Normals
  79990. this._linesNormals.push(p1.x);
  79991. this._linesNormals.push(p1.y);
  79992. this._linesNormals.push(p1.z);
  79993. this._linesNormals.push(-1);
  79994. this._linesNormals.push(p1.x);
  79995. this._linesNormals.push(p1.y);
  79996. this._linesNormals.push(p1.z);
  79997. this._linesNormals.push(1);
  79998. this._linesNormals.push(p0.x);
  79999. this._linesNormals.push(p0.y);
  80000. this._linesNormals.push(p0.z);
  80001. this._linesNormals.push(-1);
  80002. this._linesNormals.push(p0.x);
  80003. this._linesNormals.push(p0.y);
  80004. this._linesNormals.push(p0.z);
  80005. this._linesNormals.push(1);
  80006. // Indices
  80007. this._linesIndices.push(offset);
  80008. this._linesIndices.push(offset + 1);
  80009. this._linesIndices.push(offset + 2);
  80010. this._linesIndices.push(offset);
  80011. this._linesIndices.push(offset + 2);
  80012. this._linesIndices.push(offset + 3);
  80013. }
  80014. };
  80015. EdgesRenderer.prototype._generateEdgesLines = function () {
  80016. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80017. var indices = this._source.getIndices();
  80018. if (!indices || !positions) {
  80019. return;
  80020. }
  80021. // First let's find adjacencies
  80022. var adjacencies = new Array();
  80023. var faceNormals = new Array();
  80024. var index;
  80025. var faceAdjacencies;
  80026. // Prepare faces
  80027. for (index = 0; index < indices.length; index += 3) {
  80028. faceAdjacencies = new FaceAdjacencies();
  80029. var p0Index = indices[index];
  80030. var p1Index = indices[index + 1];
  80031. var p2Index = indices[index + 2];
  80032. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  80033. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  80034. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  80035. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  80036. faceNormal.normalize();
  80037. faceNormals.push(faceNormal);
  80038. adjacencies.push(faceAdjacencies);
  80039. }
  80040. // Scan
  80041. for (index = 0; index < adjacencies.length; index++) {
  80042. faceAdjacencies = adjacencies[index];
  80043. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  80044. var otherFaceAdjacencies = adjacencies[otherIndex];
  80045. if (faceAdjacencies.edgesConnectedCount === 3) {
  80046. break;
  80047. }
  80048. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  80049. continue;
  80050. }
  80051. var otherP0 = indices[otherIndex * 3];
  80052. var otherP1 = indices[otherIndex * 3 + 1];
  80053. var otherP2 = indices[otherIndex * 3 + 2];
  80054. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  80055. var otherEdgeIndex = 0;
  80056. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  80057. continue;
  80058. }
  80059. switch (edgeIndex) {
  80060. case 0:
  80061. if (this._checkVerticesInsteadOfIndices) {
  80062. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80063. }
  80064. else {
  80065. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  80066. }
  80067. break;
  80068. case 1:
  80069. if (this._checkVerticesInsteadOfIndices) {
  80070. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80071. }
  80072. else {
  80073. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  80074. }
  80075. break;
  80076. case 2:
  80077. if (this._checkVerticesInsteadOfIndices) {
  80078. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80079. }
  80080. else {
  80081. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  80082. }
  80083. break;
  80084. }
  80085. if (otherEdgeIndex === -1) {
  80086. continue;
  80087. }
  80088. faceAdjacencies.edges[edgeIndex] = otherIndex;
  80089. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  80090. faceAdjacencies.edgesConnectedCount++;
  80091. otherFaceAdjacencies.edgesConnectedCount++;
  80092. if (faceAdjacencies.edgesConnectedCount === 3) {
  80093. break;
  80094. }
  80095. }
  80096. }
  80097. }
  80098. // Create lines
  80099. for (index = 0; index < adjacencies.length; index++) {
  80100. // 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
  80101. var current = adjacencies[index];
  80102. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  80103. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  80104. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  80105. }
  80106. // Merge into a single mesh
  80107. var engine = this._source.getScene().getEngine();
  80108. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  80109. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  80110. this._ib = engine.createIndexBuffer(this._linesIndices);
  80111. this._indicesCount = this._linesIndices.length;
  80112. };
  80113. EdgesRenderer.prototype.render = function () {
  80114. var scene = this._source.getScene();
  80115. if (!this._lineShader.isReady() || !scene.activeCamera) {
  80116. return;
  80117. }
  80118. var engine = scene.getEngine();
  80119. this._lineShader._preBind();
  80120. // VBOs
  80121. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  80122. scene.resetCachedMaterial();
  80123. this._lineShader.setColor4("color", this._source.edgesColor);
  80124. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  80125. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  80126. }
  80127. else {
  80128. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  80129. }
  80130. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  80131. this._lineShader.bind(this._source.getWorldMatrix());
  80132. // Draw order
  80133. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  80134. this._lineShader.unbind();
  80135. engine.setDepthWrite(true);
  80136. };
  80137. return EdgesRenderer;
  80138. }());
  80139. BABYLON.EdgesRenderer = EdgesRenderer;
  80140. })(BABYLON || (BABYLON = {}));
  80141. //# sourceMappingURL=babylon.edgesRenderer.js.map
  80142. var BABYLON;
  80143. (function (BABYLON) {
  80144. /**
  80145. * Special Glow Blur post process only blurring the alpha channel
  80146. * It enforces keeping the most luminous color in the color channel.
  80147. */
  80148. var GlowBlurPostProcess = /** @class */ (function (_super) {
  80149. __extends(GlowBlurPostProcess, _super);
  80150. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  80151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80152. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  80153. _this.direction = direction;
  80154. _this.kernel = kernel;
  80155. _this.onApplyObservable.add(function (effect) {
  80156. effect.setFloat2("screenSize", _this.width, _this.height);
  80157. effect.setVector2("direction", _this.direction);
  80158. effect.setFloat("blurWidth", _this.kernel);
  80159. });
  80160. return _this;
  80161. }
  80162. return GlowBlurPostProcess;
  80163. }(BABYLON.PostProcess));
  80164. /**
  80165. * The highlight layer Helps adding a glow effect around a mesh.
  80166. *
  80167. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  80168. * glowy meshes to your scene.
  80169. *
  80170. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  80171. */
  80172. var HighlightLayer = /** @class */ (function () {
  80173. /**
  80174. * Instantiates a new highlight Layer and references it to the scene..
  80175. * @param name The name of the layer
  80176. * @param scene The scene to use the layer in
  80177. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  80178. */
  80179. function HighlightLayer(name, scene, options) {
  80180. this.name = name;
  80181. this._vertexBuffers = {};
  80182. this._mainTextureDesiredSize = { width: 0, height: 0 };
  80183. this._meshes = {};
  80184. this._maxSize = 0;
  80185. this._shouldRender = false;
  80186. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  80187. this._excludedMeshes = {};
  80188. /**
  80189. * Specifies whether or not the inner glow is ACTIVE in the layer.
  80190. */
  80191. this.innerGlow = true;
  80192. /**
  80193. * Specifies whether or not the outer glow is ACTIVE in the layer.
  80194. */
  80195. this.outerGlow = true;
  80196. /**
  80197. * Specifies wether the highlight layer is enabled or not.
  80198. */
  80199. this.isEnabled = true;
  80200. /**
  80201. * An event triggered when the highlight layer has been disposed.
  80202. * @type {BABYLON.Observable}
  80203. */
  80204. this.onDisposeObservable = new BABYLON.Observable();
  80205. /**
  80206. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  80207. * @type {BABYLON.Observable}
  80208. */
  80209. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  80210. /**
  80211. * An event triggered when the highlight layer is being blurred.
  80212. * @type {BABYLON.Observable}
  80213. */
  80214. this.onBeforeBlurObservable = new BABYLON.Observable();
  80215. /**
  80216. * An event triggered when the highlight layer has been blurred.
  80217. * @type {BABYLON.Observable}
  80218. */
  80219. this.onAfterBlurObservable = new BABYLON.Observable();
  80220. /**
  80221. * An event triggered when the glowing blurred texture is being merged in the scene.
  80222. * @type {BABYLON.Observable}
  80223. */
  80224. this.onBeforeComposeObservable = new BABYLON.Observable();
  80225. /**
  80226. * An event triggered when the glowing blurred texture has been merged in the scene.
  80227. * @type {BABYLON.Observable}
  80228. */
  80229. this.onAfterComposeObservable = new BABYLON.Observable();
  80230. /**
  80231. * An event triggered when the highlight layer changes its size.
  80232. * @type {BABYLON.Observable}
  80233. */
  80234. this.onSizeChangedObservable = new BABYLON.Observable();
  80235. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80236. var engine = scene.getEngine();
  80237. this._engine = engine;
  80238. this._maxSize = this._engine.getCaps().maxTextureSize;
  80239. this._scene.highlightLayers.push(this);
  80240. // Warn on stencil.
  80241. if (!this._engine.isStencilEnable) {
  80242. 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 }");
  80243. }
  80244. // Adapt options
  80245. this._options = options || {
  80246. mainTextureRatio: 0.5,
  80247. blurTextureSizeRatio: 0.5,
  80248. blurHorizontalSize: 1.0,
  80249. blurVerticalSize: 1.0,
  80250. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  80251. camera: null
  80252. };
  80253. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  80254. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  80255. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  80256. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  80257. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  80258. // VBO
  80259. var vertices = [];
  80260. vertices.push(1, 1);
  80261. vertices.push(-1, 1);
  80262. vertices.push(-1, -1);
  80263. vertices.push(1, -1);
  80264. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80266. this._createIndexBuffer();
  80267. // Effect
  80268. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  80269. // Render target
  80270. this.setMainTextureSize();
  80271. // Create Textures and post processes
  80272. this.createTextureAndPostProcesses();
  80273. }
  80274. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  80275. /**
  80276. * Gets the horizontal size of the blur.
  80277. */
  80278. get: function () {
  80279. return this._horizontalBlurPostprocess.kernel;
  80280. },
  80281. /**
  80282. * Specifies the horizontal size of the blur.
  80283. */
  80284. set: function (value) {
  80285. this._horizontalBlurPostprocess.kernel = value;
  80286. },
  80287. enumerable: true,
  80288. configurable: true
  80289. });
  80290. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  80291. /**
  80292. * Gets the vertical size of the blur.
  80293. */
  80294. get: function () {
  80295. return this._verticalBlurPostprocess.kernel;
  80296. },
  80297. /**
  80298. * Specifies the vertical size of the blur.
  80299. */
  80300. set: function (value) {
  80301. this._verticalBlurPostprocess.kernel = value;
  80302. },
  80303. enumerable: true,
  80304. configurable: true
  80305. });
  80306. Object.defineProperty(HighlightLayer.prototype, "camera", {
  80307. /**
  80308. * Gets the camera attached to the layer.
  80309. */
  80310. get: function () {
  80311. return this._options.camera;
  80312. },
  80313. enumerable: true,
  80314. configurable: true
  80315. });
  80316. HighlightLayer.prototype._createIndexBuffer = function () {
  80317. var engine = this._scene.getEngine();
  80318. // Indices
  80319. var indices = [];
  80320. indices.push(0);
  80321. indices.push(1);
  80322. indices.push(2);
  80323. indices.push(0);
  80324. indices.push(2);
  80325. indices.push(3);
  80326. this._indexBuffer = engine.createIndexBuffer(indices);
  80327. };
  80328. HighlightLayer.prototype._rebuild = function () {
  80329. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80330. if (vb) {
  80331. vb._rebuild();
  80332. }
  80333. this._createIndexBuffer();
  80334. };
  80335. /**
  80336. * Creates the render target textures and post processes used in the highlight layer.
  80337. */
  80338. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  80339. var _this = this;
  80340. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  80341. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  80342. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  80343. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  80344. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  80345. width: this._mainTextureDesiredSize.width,
  80346. height: this._mainTextureDesiredSize.height
  80347. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80348. this._mainTexture.activeCamera = this._options.camera;
  80349. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80350. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80351. this._mainTexture.anisotropicFilteringLevel = 1;
  80352. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80353. this._mainTexture.renderParticles = false;
  80354. this._mainTexture.renderList = null;
  80355. this._mainTexture.ignoreCameraViewport = true;
  80356. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  80357. width: blurTextureWidth,
  80358. height: blurTextureHeight
  80359. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80360. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80361. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80362. this._blurTexture.anisotropicFilteringLevel = 16;
  80363. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80364. this._blurTexture.renderParticles = false;
  80365. this._blurTexture.ignoreCameraViewport = true;
  80366. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80367. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  80368. effect.setTexture("textureSampler", _this._mainTexture);
  80369. });
  80370. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  80371. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80372. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80373. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80374. });
  80375. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80376. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80377. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80378. });
  80379. }
  80380. else {
  80381. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80382. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80383. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80384. });
  80385. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80386. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80387. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80388. });
  80389. }
  80390. this._mainTexture.onAfterUnbindObservable.add(function () {
  80391. _this.onBeforeBlurObservable.notifyObservers(_this);
  80392. var internalTexture = _this._blurTexture.getInternalTexture();
  80393. if (internalTexture) {
  80394. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  80395. }
  80396. _this.onAfterBlurObservable.notifyObservers(_this);
  80397. });
  80398. // Custom render function
  80399. var renderSubMesh = function (subMesh) {
  80400. if (!_this._meshes) {
  80401. return;
  80402. }
  80403. var material = subMesh.getMaterial();
  80404. var mesh = subMesh.getRenderingMesh();
  80405. var scene = _this._scene;
  80406. var engine = scene.getEngine();
  80407. if (!material) {
  80408. return;
  80409. }
  80410. // Do not block in blend mode.
  80411. if (material.needAlphaBlendingForMesh(mesh)) {
  80412. return;
  80413. }
  80414. // Culling
  80415. engine.setState(material.backFaceCulling);
  80416. // Managing instances
  80417. var batch = mesh._getInstancesRenderList(subMesh._id);
  80418. if (batch.mustReturn) {
  80419. return;
  80420. }
  80421. // Excluded Mesh
  80422. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80423. return;
  80424. }
  80425. ;
  80426. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80427. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  80428. var emissiveTexture = null;
  80429. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80430. emissiveTexture = material.emissiveTexture;
  80431. }
  80432. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  80433. engine.enableEffect(_this._glowMapGenerationEffect);
  80434. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  80435. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  80436. if (highlightLayerMesh) {
  80437. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  80438. }
  80439. else {
  80440. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  80441. }
  80442. // Alpha test
  80443. if (material && material.needAlphaTesting()) {
  80444. var alphaTexture = material.getAlphaTestTexture();
  80445. if (alphaTexture) {
  80446. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  80447. var textureMatrix = alphaTexture.getTextureMatrix();
  80448. if (textureMatrix) {
  80449. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  80450. }
  80451. }
  80452. }
  80453. // Glow emissive only
  80454. if (emissiveTexture) {
  80455. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  80456. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  80457. }
  80458. // Bones
  80459. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80460. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80461. }
  80462. // Draw
  80463. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  80464. }
  80465. else {
  80466. // Need to reset refresh rate of the shadowMap
  80467. _this._mainTexture.resetRefreshCounter();
  80468. }
  80469. };
  80470. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80471. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  80472. var index;
  80473. var engine = _this._scene.getEngine();
  80474. if (depthOnlySubMeshes.length) {
  80475. engine.setColorWrite(false);
  80476. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80477. renderSubMesh(depthOnlySubMeshes.data[index]);
  80478. }
  80479. engine.setColorWrite(true);
  80480. }
  80481. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80482. renderSubMesh(opaqueSubMeshes.data[index]);
  80483. }
  80484. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80485. renderSubMesh(alphaTestSubMeshes.data[index]);
  80486. }
  80487. for (index = 0; index < transparentSubMeshes.length; index++) {
  80488. renderSubMesh(transparentSubMeshes.data[index]);
  80489. }
  80490. };
  80491. this._mainTexture.onClearObservable.add(function (engine) {
  80492. engine.clear(HighlightLayer.neutralColor, true, true, true);
  80493. });
  80494. };
  80495. /**
  80496. * Checks for the readiness of the element composing the layer.
  80497. * @param subMesh the mesh to check for
  80498. * @param useInstances specify wether or not to use instances to render the mesh
  80499. * @param emissiveTexture the associated emissive texture used to generate the glow
  80500. * @return true if ready otherwise, false
  80501. */
  80502. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  80503. var material = subMesh.getMaterial();
  80504. var mesh = subMesh.getRenderingMesh();
  80505. if (!material || !mesh || !this._meshes) {
  80506. return false;
  80507. }
  80508. var emissiveTexture = null;
  80509. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  80510. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80511. emissiveTexture = material.emissiveTexture;
  80512. }
  80513. return this._isReady(subMesh, useInstances, emissiveTexture);
  80514. };
  80515. /**
  80516. * Checks for the readiness of the element composing the layer.
  80517. * @param subMesh the mesh to check for
  80518. * @param useInstances specify wether or not to use instances to render the mesh
  80519. * @param emissiveTexture the associated emissive texture used to generate the glow
  80520. * @return true if ready otherwise, false
  80521. */
  80522. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  80523. var material = subMesh.getMaterial();
  80524. if (!material) {
  80525. return false;
  80526. }
  80527. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  80528. return false;
  80529. }
  80530. var defines = [];
  80531. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80532. var mesh = subMesh.getMesh();
  80533. var uv1 = false;
  80534. var uv2 = false;
  80535. // Alpha test
  80536. if (material && material.needAlphaTesting()) {
  80537. var alphaTexture = material.getAlphaTestTexture();
  80538. if (alphaTexture) {
  80539. defines.push("#define ALPHATEST");
  80540. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80541. alphaTexture.coordinatesIndex === 1) {
  80542. defines.push("#define DIFFUSEUV2");
  80543. uv2 = true;
  80544. }
  80545. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80546. defines.push("#define DIFFUSEUV1");
  80547. uv1 = true;
  80548. }
  80549. }
  80550. }
  80551. // Emissive
  80552. if (emissiveTexture) {
  80553. defines.push("#define EMISSIVE");
  80554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80555. emissiveTexture.coordinatesIndex === 1) {
  80556. defines.push("#define EMISSIVEUV2");
  80557. uv2 = true;
  80558. }
  80559. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80560. defines.push("#define EMISSIVEUV1");
  80561. uv1 = true;
  80562. }
  80563. }
  80564. if (uv1) {
  80565. attribs.push(BABYLON.VertexBuffer.UVKind);
  80566. defines.push("#define UV1");
  80567. }
  80568. if (uv2) {
  80569. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80570. defines.push("#define UV2");
  80571. }
  80572. // Bones
  80573. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80574. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80575. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80576. if (mesh.numBoneInfluencers > 4) {
  80577. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80578. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80579. }
  80580. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80581. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80582. }
  80583. else {
  80584. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80585. }
  80586. // Instances
  80587. if (useInstances) {
  80588. defines.push("#define INSTANCES");
  80589. attribs.push("world0");
  80590. attribs.push("world1");
  80591. attribs.push("world2");
  80592. attribs.push("world3");
  80593. }
  80594. // Get correct effect
  80595. var join = defines.join("\n");
  80596. if (this._cachedDefines !== join) {
  80597. this._cachedDefines = join;
  80598. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  80599. }
  80600. return this._glowMapGenerationEffect.isReady();
  80601. };
  80602. /**
  80603. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  80604. */
  80605. HighlightLayer.prototype.render = function () {
  80606. var currentEffect = this._glowMapMergeEffect;
  80607. // Check
  80608. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  80609. return;
  80610. var engine = this._scene.getEngine();
  80611. this.onBeforeComposeObservable.notifyObservers(this);
  80612. // Render
  80613. engine.enableEffect(currentEffect);
  80614. engine.setState(false);
  80615. // Cache
  80616. var previousStencilBuffer = engine.getStencilBuffer();
  80617. var previousStencilFunction = engine.getStencilFunction();
  80618. var previousStencilMask = engine.getStencilMask();
  80619. var previousStencilOperationPass = engine.getStencilOperationPass();
  80620. var previousStencilOperationFail = engine.getStencilOperationFail();
  80621. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  80622. var previousAlphaMode = engine.getAlphaMode();
  80623. // Texture
  80624. currentEffect.setTexture("textureSampler", this._blurTexture);
  80625. // VBOs
  80626. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80627. // Stencil operations
  80628. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  80629. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  80630. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  80631. // Draw order
  80632. engine.setAlphaMode(this._options.alphaBlendingMode);
  80633. engine.setStencilMask(0x00);
  80634. engine.setStencilBuffer(true);
  80635. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  80636. if (this.outerGlow) {
  80637. currentEffect.setFloat("offset", 0);
  80638. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  80639. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80640. }
  80641. if (this.innerGlow) {
  80642. currentEffect.setFloat("offset", 1);
  80643. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  80644. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80645. }
  80646. // Restore Cache
  80647. engine.setStencilFunction(previousStencilFunction);
  80648. engine.setStencilMask(previousStencilMask);
  80649. engine.setAlphaMode(previousAlphaMode);
  80650. engine.setStencilBuffer(previousStencilBuffer);
  80651. engine.setStencilOperationPass(previousStencilOperationPass);
  80652. engine.setStencilOperationFail(previousStencilOperationFail);
  80653. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  80654. engine._stencilState.reset();
  80655. this.onAfterComposeObservable.notifyObservers(this);
  80656. // Handle size changes.
  80657. var size = this._mainTexture.getSize();
  80658. this.setMainTextureSize();
  80659. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  80660. // Recreate RTT and post processes on size change.
  80661. this.onSizeChangedObservable.notifyObservers(this);
  80662. this.disposeTextureAndPostProcesses();
  80663. this.createTextureAndPostProcesses();
  80664. }
  80665. };
  80666. /**
  80667. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  80668. * @param mesh The mesh to exclude from the highlight layer
  80669. */
  80670. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  80671. if (!this._excludedMeshes) {
  80672. return;
  80673. }
  80674. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80675. if (!meshExcluded) {
  80676. this._excludedMeshes[mesh.uniqueId] = {
  80677. mesh: mesh,
  80678. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  80679. mesh.getEngine().setStencilBuffer(false);
  80680. }),
  80681. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  80682. mesh.getEngine().setStencilBuffer(true);
  80683. }),
  80684. };
  80685. }
  80686. };
  80687. /**
  80688. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  80689. * @param mesh The mesh to highlight
  80690. */
  80691. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  80692. if (!this._excludedMeshes) {
  80693. return;
  80694. }
  80695. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80696. if (meshExcluded) {
  80697. if (meshExcluded.beforeRender) {
  80698. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  80699. }
  80700. if (meshExcluded.afterRender) {
  80701. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  80702. }
  80703. }
  80704. this._excludedMeshes[mesh.uniqueId] = null;
  80705. };
  80706. /**
  80707. * Determine if a given mesh will be highlighted by the current HighlightLayer
  80708. * @param mesh mesh to test
  80709. * @returns true if the mesh will be highlighted by the current HighlightLayer
  80710. */
  80711. HighlightLayer.prototype.hasMesh = function (mesh) {
  80712. if (!this._meshes) {
  80713. return false;
  80714. }
  80715. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  80716. };
  80717. /**
  80718. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  80719. * @param mesh The mesh to highlight
  80720. * @param color The color of the highlight
  80721. * @param glowEmissiveOnly Extract the glow from the emissive texture
  80722. */
  80723. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  80724. var _this = this;
  80725. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  80726. if (!this._meshes) {
  80727. return;
  80728. }
  80729. var meshHighlight = this._meshes[mesh.uniqueId];
  80730. if (meshHighlight) {
  80731. meshHighlight.color = color;
  80732. }
  80733. else {
  80734. this._meshes[mesh.uniqueId] = {
  80735. mesh: mesh,
  80736. color: color,
  80737. // Lambda required for capture due to Observable this context
  80738. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  80739. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80740. _this.defaultStencilReference(mesh);
  80741. }
  80742. else {
  80743. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  80744. }
  80745. }),
  80746. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  80747. glowEmissiveOnly: glowEmissiveOnly
  80748. };
  80749. }
  80750. this._shouldRender = true;
  80751. };
  80752. /**
  80753. * Remove a mesh from the highlight layer in order to make it stop glowing.
  80754. * @param mesh The mesh to highlight
  80755. */
  80756. HighlightLayer.prototype.removeMesh = function (mesh) {
  80757. if (!this._meshes) {
  80758. return;
  80759. }
  80760. var meshHighlight = this._meshes[mesh.uniqueId];
  80761. if (meshHighlight) {
  80762. if (meshHighlight.observerHighlight) {
  80763. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80764. }
  80765. if (meshHighlight.observerDefault) {
  80766. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80767. }
  80768. delete this._meshes[mesh.uniqueId];
  80769. }
  80770. this._shouldRender = false;
  80771. for (var meshHighlightToCheck in this._meshes) {
  80772. if (this._meshes[meshHighlightToCheck]) {
  80773. this._shouldRender = true;
  80774. break;
  80775. }
  80776. }
  80777. };
  80778. /**
  80779. * Returns true if the layer contains information to display, otherwise false.
  80780. */
  80781. HighlightLayer.prototype.shouldRender = function () {
  80782. return this.isEnabled && this._shouldRender;
  80783. };
  80784. /**
  80785. * Sets the main texture desired size which is the closest power of two
  80786. * of the engine canvas size.
  80787. */
  80788. HighlightLayer.prototype.setMainTextureSize = function () {
  80789. if (this._options.mainTextureFixedSize) {
  80790. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  80791. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  80792. }
  80793. else {
  80794. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  80795. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  80796. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  80797. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  80798. }
  80799. };
  80800. /**
  80801. * Force the stencil to the normal expected value for none glowing parts
  80802. */
  80803. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  80804. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  80805. };
  80806. /**
  80807. * Dispose only the render target textures and post process.
  80808. */
  80809. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  80810. this._blurTexture.dispose();
  80811. this._mainTexture.dispose();
  80812. this._downSamplePostprocess.dispose();
  80813. this._horizontalBlurPostprocess.dispose();
  80814. this._verticalBlurPostprocess.dispose();
  80815. };
  80816. /**
  80817. * Dispose the highlight layer and free resources.
  80818. */
  80819. HighlightLayer.prototype.dispose = function () {
  80820. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80821. if (vertexBuffer) {
  80822. vertexBuffer.dispose();
  80823. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80824. }
  80825. if (this._indexBuffer) {
  80826. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80827. this._indexBuffer = null;
  80828. }
  80829. // Clean textures and post processes
  80830. this.disposeTextureAndPostProcesses();
  80831. if (this._meshes) {
  80832. // Clean mesh references
  80833. for (var id in this._meshes) {
  80834. var meshHighlight = this._meshes[id];
  80835. if (meshHighlight && meshHighlight.mesh) {
  80836. if (meshHighlight.observerHighlight) {
  80837. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80838. }
  80839. if (meshHighlight.observerDefault) {
  80840. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80841. }
  80842. }
  80843. }
  80844. this._meshes = null;
  80845. }
  80846. if (this._excludedMeshes) {
  80847. for (var id in this._excludedMeshes) {
  80848. var meshHighlight = this._excludedMeshes[id];
  80849. if (meshHighlight) {
  80850. if (meshHighlight.beforeRender) {
  80851. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  80852. }
  80853. if (meshHighlight.afterRender) {
  80854. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  80855. }
  80856. }
  80857. }
  80858. this._excludedMeshes = null;
  80859. }
  80860. // Remove from scene
  80861. var index = this._scene.highlightLayers.indexOf(this, 0);
  80862. if (index > -1) {
  80863. this._scene.highlightLayers.splice(index, 1);
  80864. }
  80865. // Callback
  80866. this.onDisposeObservable.notifyObservers(this);
  80867. this.onDisposeObservable.clear();
  80868. this.onBeforeRenderMainTextureObservable.clear();
  80869. this.onBeforeBlurObservable.clear();
  80870. this.onBeforeComposeObservable.clear();
  80871. this.onAfterComposeObservable.clear();
  80872. this.onSizeChangedObservable.clear();
  80873. };
  80874. /**
  80875. * The neutral color used during the preparation of the glow effect.
  80876. * This is black by default as the blend operation is a blend operation.
  80877. */
  80878. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  80879. /**
  80880. * Stencil value used for glowing meshes.
  80881. */
  80882. HighlightLayer.glowingMeshStencilReference = 0x02;
  80883. /**
  80884. * Stencil value used for the other meshes in the scene.
  80885. */
  80886. HighlightLayer.normalMeshStencilReference = 0x01;
  80887. return HighlightLayer;
  80888. }());
  80889. BABYLON.HighlightLayer = HighlightLayer;
  80890. })(BABYLON || (BABYLON = {}));
  80891. //# sourceMappingURL=babylon.highlightlayer.js.map
  80892. var BABYLON;
  80893. (function (BABYLON) {
  80894. /**
  80895. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  80896. */
  80897. var AssetTaskState;
  80898. (function (AssetTaskState) {
  80899. /**
  80900. * Initialization
  80901. */
  80902. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  80903. /**
  80904. * Running
  80905. */
  80906. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  80907. /**
  80908. * Done
  80909. */
  80910. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  80911. /**
  80912. * Error
  80913. */
  80914. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  80915. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  80916. /**
  80917. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  80918. */
  80919. var AbstractAssetTask = /** @class */ (function () {
  80920. /**
  80921. * Creates a new {BABYLON.AssetsManager}
  80922. * @param name defines the name of the task
  80923. */
  80924. function AbstractAssetTask(
  80925. /**
  80926. * Task name
  80927. */ name) {
  80928. this.name = name;
  80929. this._isCompleted = false;
  80930. this._taskState = AssetTaskState.INIT;
  80931. }
  80932. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  80933. /**
  80934. * Get if the task is completed
  80935. */
  80936. get: function () {
  80937. return this._isCompleted;
  80938. },
  80939. enumerable: true,
  80940. configurable: true
  80941. });
  80942. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  80943. /**
  80944. * Gets the current state of the task
  80945. */
  80946. get: function () {
  80947. return this._taskState;
  80948. },
  80949. enumerable: true,
  80950. configurable: true
  80951. });
  80952. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  80953. /**
  80954. * Gets the current error object (if task is in error)
  80955. */
  80956. get: function () {
  80957. return this._errorObject;
  80958. },
  80959. enumerable: true,
  80960. configurable: true
  80961. });
  80962. /**
  80963. * Internal only
  80964. * @ignore
  80965. */
  80966. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  80967. if (this._errorObject) {
  80968. return;
  80969. }
  80970. this._errorObject = {
  80971. message: message,
  80972. exception: exception
  80973. };
  80974. };
  80975. /**
  80976. * Execute the current task
  80977. * @param scene defines the scene where you want your assets to be loaded
  80978. * @param onSuccess is a callback called when the task is successfully executed
  80979. * @param onError is a callback called if an error occurs
  80980. */
  80981. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80982. var _this = this;
  80983. this._taskState = AssetTaskState.RUNNING;
  80984. this.runTask(scene, function () {
  80985. _this.onDoneCallback(onSuccess, onError);
  80986. }, function (msg, exception) {
  80987. _this.onErrorCallback(onError, msg, exception);
  80988. });
  80989. };
  80990. /**
  80991. * Execute the current task
  80992. * @param scene defines the scene where you want your assets to be loaded
  80993. * @param onSuccess is a callback called when the task is successfully executed
  80994. * @param onError is a callback called if an error occurs
  80995. */
  80996. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80997. throw new Error("runTask is not implemented");
  80998. };
  80999. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  81000. this._taskState = AssetTaskState.ERROR;
  81001. this._errorObject = {
  81002. message: message,
  81003. exception: exception
  81004. };
  81005. if (this.onError) {
  81006. this.onError(this, message, exception);
  81007. }
  81008. onError();
  81009. };
  81010. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  81011. try {
  81012. this._taskState = AssetTaskState.DONE;
  81013. this._isCompleted = true;
  81014. if (this.onSuccess) {
  81015. this.onSuccess(this);
  81016. }
  81017. onSuccess();
  81018. }
  81019. catch (e) {
  81020. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  81021. }
  81022. };
  81023. return AbstractAssetTask;
  81024. }());
  81025. BABYLON.AbstractAssetTask = AbstractAssetTask;
  81026. /**
  81027. * Class used to share progress information about assets loading
  81028. */
  81029. var AssetsProgressEvent = /** @class */ (function () {
  81030. /**
  81031. * Creates a {BABYLON.AssetsProgressEvent}
  81032. * @param remainingCount defines the number of remaining tasks to process
  81033. * @param totalCount defines the total number of tasks
  81034. * @param task defines the task that was just processed
  81035. */
  81036. function AssetsProgressEvent(remainingCount, totalCount, task) {
  81037. this.remainingCount = remainingCount;
  81038. this.totalCount = totalCount;
  81039. this.task = task;
  81040. }
  81041. return AssetsProgressEvent;
  81042. }());
  81043. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  81044. /**
  81045. * Define a task used by {BABYLON.AssetsManager} to load meshes
  81046. */
  81047. var MeshAssetTask = /** @class */ (function (_super) {
  81048. __extends(MeshAssetTask, _super);
  81049. /**
  81050. * Creates a new {BABYLON.MeshAssetTask}
  81051. * @param name defines the name of the task
  81052. * @param meshesNames defines the list of mesh's names you want to load
  81053. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  81054. * @param sceneFilename defines the filename of the scene to load from
  81055. */
  81056. function MeshAssetTask(
  81057. /**
  81058. * Defines the name of the task
  81059. */
  81060. name,
  81061. /**
  81062. * Defines the list of mesh's names you want to load
  81063. */
  81064. meshesNames,
  81065. /**
  81066. * Defines the root url to use as a base to load your meshes and associated resources
  81067. */
  81068. rootUrl,
  81069. /**
  81070. * Defines the filename of the scene to load from
  81071. */
  81072. sceneFilename) {
  81073. var _this = _super.call(this, name) || this;
  81074. _this.name = name;
  81075. _this.meshesNames = meshesNames;
  81076. _this.rootUrl = rootUrl;
  81077. _this.sceneFilename = sceneFilename;
  81078. return _this;
  81079. }
  81080. /**
  81081. * Execute the current task
  81082. * @param scene defines the scene where you want your assets to be loaded
  81083. * @param onSuccess is a callback called when the task is successfully executed
  81084. * @param onError is a callback called if an error occurs
  81085. */
  81086. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81087. var _this = this;
  81088. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  81089. _this.loadedMeshes = meshes;
  81090. _this.loadedParticleSystems = particleSystems;
  81091. _this.loadedSkeletons = skeletons;
  81092. onSuccess();
  81093. }, null, function (scene, message, exception) {
  81094. onError(message, exception);
  81095. });
  81096. };
  81097. return MeshAssetTask;
  81098. }(AbstractAssetTask));
  81099. BABYLON.MeshAssetTask = MeshAssetTask;
  81100. /**
  81101. * Define a task used by {BABYLON.AssetsManager} to load text content
  81102. */
  81103. var TextFileAssetTask = /** @class */ (function (_super) {
  81104. __extends(TextFileAssetTask, _super);
  81105. /**
  81106. * Creates a new TextFileAssetTask object
  81107. * @param name defines the name of the task
  81108. * @param url defines the location of the file to load
  81109. */
  81110. function TextFileAssetTask(
  81111. /**
  81112. * Defines the name of the task
  81113. */
  81114. name,
  81115. /**
  81116. * Defines the location of the file to load
  81117. */
  81118. url) {
  81119. var _this = _super.call(this, name) || this;
  81120. _this.name = name;
  81121. _this.url = url;
  81122. return _this;
  81123. }
  81124. /**
  81125. * Execute the current task
  81126. * @param scene defines the scene where you want your assets to be loaded
  81127. * @param onSuccess is a callback called when the task is successfully executed
  81128. * @param onError is a callback called if an error occurs
  81129. */
  81130. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81131. var _this = this;
  81132. scene._loadFile(this.url, function (data) {
  81133. _this.text = data;
  81134. onSuccess();
  81135. }, undefined, false, true, function (request, exception) {
  81136. if (request) {
  81137. onError(request.status + " " + request.statusText, exception);
  81138. }
  81139. });
  81140. };
  81141. return TextFileAssetTask;
  81142. }(AbstractAssetTask));
  81143. BABYLON.TextFileAssetTask = TextFileAssetTask;
  81144. /**
  81145. * Define a task used by {BABYLON.AssetsManager} to load binary data
  81146. */
  81147. var BinaryFileAssetTask = /** @class */ (function (_super) {
  81148. __extends(BinaryFileAssetTask, _super);
  81149. /**
  81150. * Creates a new BinaryFileAssetTask object
  81151. * @param name defines the name of the new task
  81152. * @param url defines the location of the file to load
  81153. */
  81154. function BinaryFileAssetTask(
  81155. /**
  81156. * Defines the name of the task
  81157. */
  81158. name,
  81159. /**
  81160. * Defines the location of the file to load
  81161. */
  81162. url) {
  81163. var _this = _super.call(this, name) || this;
  81164. _this.name = name;
  81165. _this.url = url;
  81166. return _this;
  81167. }
  81168. /**
  81169. * Execute the current task
  81170. * @param scene defines the scene where you want your assets to be loaded
  81171. * @param onSuccess is a callback called when the task is successfully executed
  81172. * @param onError is a callback called if an error occurs
  81173. */
  81174. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81175. var _this = this;
  81176. scene._loadFile(this.url, function (data) {
  81177. _this.data = data;
  81178. onSuccess();
  81179. }, undefined, true, true, function (request, exception) {
  81180. if (request) {
  81181. onError(request.status + " " + request.statusText, exception);
  81182. }
  81183. });
  81184. };
  81185. return BinaryFileAssetTask;
  81186. }(AbstractAssetTask));
  81187. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  81188. /**
  81189. * Define a task used by {BABYLON.AssetsManager} to load images
  81190. */
  81191. var ImageAssetTask = /** @class */ (function (_super) {
  81192. __extends(ImageAssetTask, _super);
  81193. /**
  81194. * Creates a new ImageAssetTask
  81195. * @param name defines the name of the task
  81196. * @param url defines the location of the image to load
  81197. */
  81198. function ImageAssetTask(
  81199. /**
  81200. * Defines the name of the task
  81201. */
  81202. name,
  81203. /**
  81204. * Defines the location of the image to load
  81205. */
  81206. url) {
  81207. var _this = _super.call(this, name) || this;
  81208. _this.name = name;
  81209. _this.url = url;
  81210. return _this;
  81211. }
  81212. /**
  81213. * Execute the current task
  81214. * @param scene defines the scene where you want your assets to be loaded
  81215. * @param onSuccess is a callback called when the task is successfully executed
  81216. * @param onError is a callback called if an error occurs
  81217. */
  81218. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81219. var _this = this;
  81220. var img = new Image();
  81221. BABYLON.Tools.SetCorsBehavior(this.url, img);
  81222. img.onload = function () {
  81223. _this.image = img;
  81224. onSuccess();
  81225. };
  81226. img.onerror = function (err) {
  81227. onError("Error loading image", err);
  81228. };
  81229. img.src = this.url;
  81230. };
  81231. return ImageAssetTask;
  81232. }(AbstractAssetTask));
  81233. BABYLON.ImageAssetTask = ImageAssetTask;
  81234. /**
  81235. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  81236. */
  81237. var TextureAssetTask = /** @class */ (function (_super) {
  81238. __extends(TextureAssetTask, _super);
  81239. /**
  81240. * Creates a new TextureAssetTask object
  81241. * @param name defines the name of the task
  81242. * @param url defines the location of the file to load
  81243. * @param noMipmap defines if mipmap should not be generated (default is false)
  81244. * @param invertY defines if texture must be inverted on Y axis (default is false)
  81245. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81246. */
  81247. function TextureAssetTask(
  81248. /**
  81249. * Defines the name of the task
  81250. */
  81251. name,
  81252. /**
  81253. * Defines the location of the file to load
  81254. */
  81255. url,
  81256. /**
  81257. * Defines if mipmap should not be generated (default is false)
  81258. */
  81259. noMipmap,
  81260. /**
  81261. * Defines if texture must be inverted on Y axis (default is false)
  81262. */
  81263. invertY,
  81264. /**
  81265. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81266. */
  81267. samplingMode) {
  81268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81269. var _this = _super.call(this, name) || this;
  81270. _this.name = name;
  81271. _this.url = url;
  81272. _this.noMipmap = noMipmap;
  81273. _this.invertY = invertY;
  81274. _this.samplingMode = samplingMode;
  81275. return _this;
  81276. }
  81277. /**
  81278. * Execute the current task
  81279. * @param scene defines the scene where you want your assets to be loaded
  81280. * @param onSuccess is a callback called when the task is successfully executed
  81281. * @param onError is a callback called if an error occurs
  81282. */
  81283. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81284. var onload = function () {
  81285. onSuccess();
  81286. };
  81287. var onerror = function (message, exception) {
  81288. onError(message, exception);
  81289. };
  81290. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  81291. };
  81292. return TextureAssetTask;
  81293. }(AbstractAssetTask));
  81294. BABYLON.TextureAssetTask = TextureAssetTask;
  81295. /**
  81296. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  81297. */
  81298. var CubeTextureAssetTask = /** @class */ (function (_super) {
  81299. __extends(CubeTextureAssetTask, _super);
  81300. /**
  81301. * Creates a new CubeTextureAssetTask
  81302. * @param name defines the name of the task
  81303. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81304. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81305. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81306. * @param files defines the explicit list of files (undefined by default)
  81307. */
  81308. function CubeTextureAssetTask(
  81309. /**
  81310. * Defines the name of the task
  81311. */
  81312. name,
  81313. /**
  81314. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81315. */
  81316. url,
  81317. /**
  81318. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81319. */
  81320. extensions,
  81321. /**
  81322. * Defines if mipmaps should not be generated (default is false)
  81323. */
  81324. noMipmap,
  81325. /**
  81326. * Defines the explicit list of files (undefined by default)
  81327. */
  81328. files) {
  81329. var _this = _super.call(this, name) || this;
  81330. _this.name = name;
  81331. _this.url = url;
  81332. _this.extensions = extensions;
  81333. _this.noMipmap = noMipmap;
  81334. _this.files = files;
  81335. return _this;
  81336. }
  81337. /**
  81338. * Execute the current task
  81339. * @param scene defines the scene where you want your assets to be loaded
  81340. * @param onSuccess is a callback called when the task is successfully executed
  81341. * @param onError is a callback called if an error occurs
  81342. */
  81343. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81344. var onload = function () {
  81345. onSuccess();
  81346. };
  81347. var onerror = function (message, exception) {
  81348. onError(message, exception);
  81349. };
  81350. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  81351. };
  81352. return CubeTextureAssetTask;
  81353. }(AbstractAssetTask));
  81354. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  81355. /**
  81356. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  81357. */
  81358. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  81359. __extends(HDRCubeTextureAssetTask, _super);
  81360. /**
  81361. * Creates a new HDRCubeTextureAssetTask object
  81362. * @param name defines the name of the task
  81363. * @param url defines the location of the file to load
  81364. * @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.
  81365. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81366. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81367. * @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)
  81368. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81369. */
  81370. function HDRCubeTextureAssetTask(
  81371. /**
  81372. * Defines the name of the task
  81373. */
  81374. name,
  81375. /**
  81376. * Defines the location of the file to load
  81377. */
  81378. url,
  81379. /**
  81380. * 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.
  81381. */
  81382. size,
  81383. /**
  81384. * Defines if mipmaps should not be generated (default is false)
  81385. */
  81386. noMipmap,
  81387. /**
  81388. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81389. */
  81390. generateHarmonics,
  81391. /**
  81392. * 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)
  81393. */
  81394. useInGammaSpace,
  81395. /**
  81396. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81397. */
  81398. usePMREMGenerator) {
  81399. if (noMipmap === void 0) { noMipmap = false; }
  81400. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81401. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81402. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81403. var _this = _super.call(this, name) || this;
  81404. _this.name = name;
  81405. _this.url = url;
  81406. _this.size = size;
  81407. _this.noMipmap = noMipmap;
  81408. _this.generateHarmonics = generateHarmonics;
  81409. _this.useInGammaSpace = useInGammaSpace;
  81410. _this.usePMREMGenerator = usePMREMGenerator;
  81411. return _this;
  81412. }
  81413. /**
  81414. * Execute the current task
  81415. * @param scene defines the scene where you want your assets to be loaded
  81416. * @param onSuccess is a callback called when the task is successfully executed
  81417. * @param onError is a callback called if an error occurs
  81418. */
  81419. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81420. var onload = function () {
  81421. onSuccess();
  81422. };
  81423. var onerror = function (message, exception) {
  81424. onError(message, exception);
  81425. };
  81426. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  81427. };
  81428. return HDRCubeTextureAssetTask;
  81429. }(AbstractAssetTask));
  81430. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  81431. /**
  81432. * This class can be used to easily import assets into a scene
  81433. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  81434. */
  81435. var AssetsManager = /** @class */ (function () {
  81436. /**
  81437. * Creates a new AssetsManager
  81438. * @param scene defines the scene to work on
  81439. */
  81440. function AssetsManager(scene) {
  81441. this._isLoading = false;
  81442. this._tasks = new Array();
  81443. this._waitingTasksCount = 0;
  81444. this._totalTasksCount = 0;
  81445. /**
  81446. * Observable called when all tasks are processed
  81447. */
  81448. this.onTaskSuccessObservable = new BABYLON.Observable();
  81449. /**
  81450. * Observable called when a task had an error
  81451. */
  81452. this.onTaskErrorObservable = new BABYLON.Observable();
  81453. /**
  81454. * Observable called when a task is successful
  81455. */
  81456. this.onTasksDoneObservable = new BABYLON.Observable();
  81457. /**
  81458. * Observable called when a task is done (whatever the result is)
  81459. */
  81460. this.onProgressObservable = new BABYLON.Observable();
  81461. /**
  81462. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  81463. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  81464. */
  81465. this.useDefaultLoadingScreen = true;
  81466. this._scene = scene;
  81467. }
  81468. /**
  81469. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  81470. * @param taskName defines the name of the new task
  81471. * @param meshesNames defines the name of meshes to load
  81472. * @param rootUrl defines the root url to use to locate files
  81473. * @param sceneFilename defines the filename of the scene file
  81474. * @returns a new {BABYLON.MeshAssetTask} object
  81475. */
  81476. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  81477. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  81478. this._tasks.push(task);
  81479. return task;
  81480. };
  81481. /**
  81482. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  81483. * @param taskName defines the name of the new task
  81484. * @param url defines the url of the file to load
  81485. * @returns a new {BABYLON.TextFileAssetTask} object
  81486. */
  81487. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  81488. var task = new TextFileAssetTask(taskName, url);
  81489. this._tasks.push(task);
  81490. return task;
  81491. };
  81492. /**
  81493. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  81494. * @param taskName defines the name of the new task
  81495. * @param url defines the url of the file to load
  81496. * @returns a new {BABYLON.BinaryFileAssetTask} object
  81497. */
  81498. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  81499. var task = new BinaryFileAssetTask(taskName, url);
  81500. this._tasks.push(task);
  81501. return task;
  81502. };
  81503. /**
  81504. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  81505. * @param taskName defines the name of the new task
  81506. * @param url defines the url of the file to load
  81507. * @returns a new {BABYLON.ImageAssetTask} object
  81508. */
  81509. AssetsManager.prototype.addImageTask = function (taskName, url) {
  81510. var task = new ImageAssetTask(taskName, url);
  81511. this._tasks.push(task);
  81512. return task;
  81513. };
  81514. /**
  81515. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  81516. * @param taskName defines the name of the new task
  81517. * @param url defines the url of the file to load
  81518. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81519. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  81520. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  81521. * @returns a new {BABYLON.TextureAssetTask} object
  81522. */
  81523. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  81524. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81525. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  81526. this._tasks.push(task);
  81527. return task;
  81528. };
  81529. /**
  81530. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  81531. * @param taskName defines the name of the new task
  81532. * @param url defines the url of the file to load
  81533. * @param extensions defines the extension to use to load the cube map (can be null)
  81534. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81535. * @param files defines the list of files to load (can be null)
  81536. * @returns a new {BABYLON.CubeTextureAssetTask} object
  81537. */
  81538. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  81539. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  81540. this._tasks.push(task);
  81541. return task;
  81542. };
  81543. /**
  81544. *
  81545. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  81546. * @param taskName defines the name of the new task
  81547. * @param url defines the url of the file to load
  81548. * @param size defines the size you want for the cubemap (can be null)
  81549. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81550. * @param generateHarmonics defines if you want to automatically generate (true by default)
  81551. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  81552. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  81553. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  81554. */
  81555. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  81556. if (noMipmap === void 0) { noMipmap = false; }
  81557. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81558. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81559. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81560. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  81561. this._tasks.push(task);
  81562. return task;
  81563. };
  81564. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  81565. var _this = this;
  81566. this._waitingTasksCount--;
  81567. try {
  81568. if (task.taskState === AssetTaskState.DONE) {
  81569. // Let's remove successfull tasks
  81570. BABYLON.Tools.SetImmediate(function () {
  81571. var index = _this._tasks.indexOf(task);
  81572. if (index > -1) {
  81573. _this._tasks.splice(index, 1);
  81574. }
  81575. });
  81576. }
  81577. if (this.onProgress) {
  81578. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  81579. }
  81580. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  81581. }
  81582. catch (e) {
  81583. BABYLON.Tools.Error("Error running progress callbacks.");
  81584. console.log(e);
  81585. }
  81586. if (this._waitingTasksCount === 0) {
  81587. try {
  81588. if (this.onFinish) {
  81589. this.onFinish(this._tasks);
  81590. }
  81591. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81592. }
  81593. catch (e) {
  81594. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  81595. console.log(e);
  81596. }
  81597. this._isLoading = false;
  81598. this._scene.getEngine().hideLoadingUI();
  81599. }
  81600. };
  81601. AssetsManager.prototype._runTask = function (task) {
  81602. var _this = this;
  81603. var done = function () {
  81604. try {
  81605. if (_this.onTaskSuccess) {
  81606. _this.onTaskSuccess(task);
  81607. }
  81608. _this.onTaskSuccessObservable.notifyObservers(task);
  81609. _this._decreaseWaitingTasksCount(task);
  81610. }
  81611. catch (e) {
  81612. error("Error executing task success callbacks", e);
  81613. }
  81614. };
  81615. var error = function (message, exception) {
  81616. task._setErrorObject(message, exception);
  81617. if (_this.onTaskError) {
  81618. _this.onTaskError(task);
  81619. }
  81620. _this.onTaskErrorObservable.notifyObservers(task);
  81621. _this._decreaseWaitingTasksCount(task);
  81622. };
  81623. task.run(this._scene, done, error);
  81624. };
  81625. /**
  81626. * Reset the {BABYLON.AssetsManager} and remove all tasks
  81627. * @return the current instance of the {BABYLON.AssetsManager}
  81628. */
  81629. AssetsManager.prototype.reset = function () {
  81630. this._isLoading = false;
  81631. this._tasks = new Array();
  81632. return this;
  81633. };
  81634. /**
  81635. * Start the loading process
  81636. * @return the current instance of the {BABYLON.AssetsManager}
  81637. */
  81638. AssetsManager.prototype.load = function () {
  81639. if (this._isLoading) {
  81640. return this;
  81641. }
  81642. this._isLoading = true;
  81643. this._waitingTasksCount = this._tasks.length;
  81644. this._totalTasksCount = this._tasks.length;
  81645. if (this._waitingTasksCount === 0) {
  81646. if (this.onFinish) {
  81647. this.onFinish(this._tasks);
  81648. }
  81649. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81650. return this;
  81651. }
  81652. if (this.useDefaultLoadingScreen) {
  81653. this._scene.getEngine().displayLoadingUI();
  81654. }
  81655. for (var index = 0; index < this._tasks.length; index++) {
  81656. var task = this._tasks[index];
  81657. this._runTask(task);
  81658. }
  81659. return this;
  81660. };
  81661. return AssetsManager;
  81662. }());
  81663. BABYLON.AssetsManager = AssetsManager;
  81664. })(BABYLON || (BABYLON = {}));
  81665. //# sourceMappingURL=babylon.assetsManager.js.map
  81666. var BABYLON;
  81667. (function (BABYLON) {
  81668. var serializedGeometries = [];
  81669. var serializeGeometry = function (geometry, serializationGeometries) {
  81670. if (serializedGeometries[geometry.id]) {
  81671. return;
  81672. }
  81673. if (geometry.doNotSerialize) {
  81674. return;
  81675. }
  81676. if (geometry instanceof BABYLON.BoxGeometry) {
  81677. serializationGeometries.boxes.push(geometry.serialize());
  81678. }
  81679. else if (geometry instanceof BABYLON.SphereGeometry) {
  81680. serializationGeometries.spheres.push(geometry.serialize());
  81681. }
  81682. else if (geometry instanceof BABYLON.CylinderGeometry) {
  81683. serializationGeometries.cylinders.push(geometry.serialize());
  81684. }
  81685. else if (geometry instanceof BABYLON.TorusGeometry) {
  81686. serializationGeometries.toruses.push(geometry.serialize());
  81687. }
  81688. else if (geometry instanceof BABYLON.GroundGeometry) {
  81689. serializationGeometries.grounds.push(geometry.serialize());
  81690. }
  81691. else if (geometry instanceof BABYLON.Plane) {
  81692. serializationGeometries.planes.push(geometry.serialize());
  81693. }
  81694. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  81695. serializationGeometries.torusKnots.push(geometry.serialize());
  81696. }
  81697. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  81698. throw new Error("Unknown primitive type");
  81699. }
  81700. else {
  81701. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  81702. }
  81703. serializedGeometries[geometry.id] = true;
  81704. };
  81705. var serializeMesh = function (mesh, serializationScene) {
  81706. var serializationObject = {};
  81707. // Geometry
  81708. var geometry = mesh._geometry;
  81709. if (geometry) {
  81710. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  81711. // 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
  81712. serializeGeometry(geometry, serializationScene.geometries);
  81713. }
  81714. }
  81715. // Custom
  81716. if (mesh.serialize) {
  81717. mesh.serialize(serializationObject);
  81718. }
  81719. return serializationObject;
  81720. };
  81721. var finalizeSingleMesh = function (mesh, serializationObject) {
  81722. //only works if the mesh is already loaded
  81723. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81724. //serialize material
  81725. if (mesh.material) {
  81726. if (mesh.material instanceof BABYLON.StandardMaterial) {
  81727. serializationObject.materials = serializationObject.materials || [];
  81728. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81729. serializationObject.materials.push(mesh.material.serialize());
  81730. }
  81731. }
  81732. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  81733. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  81734. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81735. serializationObject.multiMaterials.push(mesh.material.serialize());
  81736. }
  81737. }
  81738. }
  81739. //serialize geometry
  81740. var geometry = mesh._geometry;
  81741. if (geometry) {
  81742. if (!serializationObject.geometries) {
  81743. serializationObject.geometries = {};
  81744. serializationObject.geometries.boxes = [];
  81745. serializationObject.geometries.spheres = [];
  81746. serializationObject.geometries.cylinders = [];
  81747. serializationObject.geometries.toruses = [];
  81748. serializationObject.geometries.grounds = [];
  81749. serializationObject.geometries.planes = [];
  81750. serializationObject.geometries.torusKnots = [];
  81751. serializationObject.geometries.vertexData = [];
  81752. }
  81753. serializeGeometry(geometry, serializationObject.geometries);
  81754. }
  81755. // Skeletons
  81756. if (mesh.skeleton) {
  81757. serializationObject.skeletons = serializationObject.skeletons || [];
  81758. serializationObject.skeletons.push(mesh.skeleton.serialize());
  81759. }
  81760. //serialize the actual mesh
  81761. serializationObject.meshes = serializationObject.meshes || [];
  81762. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81763. }
  81764. };
  81765. var SceneSerializer = /** @class */ (function () {
  81766. function SceneSerializer() {
  81767. }
  81768. SceneSerializer.ClearCache = function () {
  81769. serializedGeometries = [];
  81770. };
  81771. SceneSerializer.Serialize = function (scene) {
  81772. var serializationObject = {};
  81773. SceneSerializer.ClearCache();
  81774. // Scene
  81775. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  81776. serializationObject.autoClear = scene.autoClear;
  81777. serializationObject.clearColor = scene.clearColor.asArray();
  81778. serializationObject.ambientColor = scene.ambientColor.asArray();
  81779. serializationObject.gravity = scene.gravity.asArray();
  81780. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  81781. serializationObject.workerCollisions = scene.workerCollisions;
  81782. // Fog
  81783. if (scene.fogMode && scene.fogMode !== 0) {
  81784. serializationObject.fogMode = scene.fogMode;
  81785. serializationObject.fogColor = scene.fogColor.asArray();
  81786. serializationObject.fogStart = scene.fogStart;
  81787. serializationObject.fogEnd = scene.fogEnd;
  81788. serializationObject.fogDensity = scene.fogDensity;
  81789. }
  81790. //Physics
  81791. if (scene.isPhysicsEnabled()) {
  81792. var physicEngine = scene.getPhysicsEngine();
  81793. if (physicEngine) {
  81794. serializationObject.physicsEnabled = true;
  81795. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  81796. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  81797. }
  81798. }
  81799. // Metadata
  81800. if (scene.metadata) {
  81801. serializationObject.metadata = scene.metadata;
  81802. }
  81803. // Morph targets
  81804. serializationObject.morphTargetManagers = [];
  81805. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  81806. var abstractMesh = _a[_i];
  81807. var manager = abstractMesh.morphTargetManager;
  81808. if (manager) {
  81809. serializationObject.morphTargetManagers.push(manager.serialize());
  81810. }
  81811. }
  81812. // Lights
  81813. serializationObject.lights = [];
  81814. var index;
  81815. var light;
  81816. for (index = 0; index < scene.lights.length; index++) {
  81817. light = scene.lights[index];
  81818. if (!light.doNotSerialize) {
  81819. serializationObject.lights.push(light.serialize());
  81820. }
  81821. }
  81822. // Cameras
  81823. serializationObject.cameras = [];
  81824. for (index = 0; index < scene.cameras.length; index++) {
  81825. var camera = scene.cameras[index];
  81826. if (!camera.doNotSerialize) {
  81827. serializationObject.cameras.push(camera.serialize());
  81828. }
  81829. }
  81830. if (scene.activeCamera) {
  81831. serializationObject.activeCameraID = scene.activeCamera.id;
  81832. }
  81833. // Animations
  81834. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  81835. // Materials
  81836. serializationObject.materials = [];
  81837. serializationObject.multiMaterials = [];
  81838. var material;
  81839. for (index = 0; index < scene.materials.length; index++) {
  81840. material = scene.materials[index];
  81841. if (!material.doNotSerialize) {
  81842. serializationObject.materials.push(material.serialize());
  81843. }
  81844. }
  81845. // MultiMaterials
  81846. serializationObject.multiMaterials = [];
  81847. for (index = 0; index < scene.multiMaterials.length; index++) {
  81848. var multiMaterial = scene.multiMaterials[index];
  81849. serializationObject.multiMaterials.push(multiMaterial.serialize());
  81850. }
  81851. // Environment texture
  81852. if (scene.environmentTexture) {
  81853. serializationObject.environmentTexture = scene.environmentTexture.name;
  81854. }
  81855. // Skeletons
  81856. serializationObject.skeletons = [];
  81857. for (index = 0; index < scene.skeletons.length; index++) {
  81858. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  81859. }
  81860. // Transform nodes
  81861. serializationObject.transformNodes = [];
  81862. for (index = 0; index < scene.transformNodes.length; index++) {
  81863. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  81864. }
  81865. // Geometries
  81866. serializationObject.geometries = {};
  81867. serializationObject.geometries.boxes = [];
  81868. serializationObject.geometries.spheres = [];
  81869. serializationObject.geometries.cylinders = [];
  81870. serializationObject.geometries.toruses = [];
  81871. serializationObject.geometries.grounds = [];
  81872. serializationObject.geometries.planes = [];
  81873. serializationObject.geometries.torusKnots = [];
  81874. serializationObject.geometries.vertexData = [];
  81875. serializedGeometries = [];
  81876. var geometries = scene.getGeometries();
  81877. for (index = 0; index < geometries.length; index++) {
  81878. var geometry = geometries[index];
  81879. if (geometry.isReady()) {
  81880. serializeGeometry(geometry, serializationObject.geometries);
  81881. }
  81882. }
  81883. // Meshes
  81884. serializationObject.meshes = [];
  81885. for (index = 0; index < scene.meshes.length; index++) {
  81886. var abstractMesh = scene.meshes[index];
  81887. if (abstractMesh instanceof BABYLON.Mesh) {
  81888. var mesh = abstractMesh;
  81889. if (!mesh.doNotSerialize) {
  81890. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81891. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81892. }
  81893. }
  81894. }
  81895. }
  81896. // Particles Systems
  81897. serializationObject.particleSystems = [];
  81898. for (index = 0; index < scene.particleSystems.length; index++) {
  81899. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  81900. }
  81901. // Lens flares
  81902. serializationObject.lensFlareSystems = [];
  81903. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  81904. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  81905. }
  81906. // Shadows
  81907. serializationObject.shadowGenerators = [];
  81908. for (index = 0; index < scene.lights.length; index++) {
  81909. light = scene.lights[index];
  81910. var shadowGenerator = light.getShadowGenerator();
  81911. if (shadowGenerator) {
  81912. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  81913. }
  81914. }
  81915. // Action Manager
  81916. if (scene.actionManager) {
  81917. serializationObject.actions = scene.actionManager.serialize("scene");
  81918. }
  81919. // Audio
  81920. serializationObject.sounds = [];
  81921. for (index = 0; index < scene.soundTracks.length; index++) {
  81922. var soundtrack = scene.soundTracks[index];
  81923. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  81924. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  81925. }
  81926. }
  81927. return serializationObject;
  81928. };
  81929. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  81930. if (withParents === void 0) { withParents = false; }
  81931. if (withChildren === void 0) { withChildren = false; }
  81932. var serializationObject = {};
  81933. SceneSerializer.ClearCache();
  81934. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  81935. if (withParents || withChildren) {
  81936. //deliberate for loop! not for each, appended should be processed as well.
  81937. for (var i = 0; i < toSerialize.length; ++i) {
  81938. if (withChildren) {
  81939. toSerialize[i].getDescendants().forEach(function (node) {
  81940. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  81941. toSerialize.push(node);
  81942. }
  81943. });
  81944. }
  81945. //make sure the array doesn't contain the object already
  81946. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  81947. toSerialize.push(toSerialize[i].parent);
  81948. }
  81949. }
  81950. }
  81951. toSerialize.forEach(function (mesh) {
  81952. finalizeSingleMesh(mesh, serializationObject);
  81953. });
  81954. return serializationObject;
  81955. };
  81956. return SceneSerializer;
  81957. }());
  81958. BABYLON.SceneSerializer = SceneSerializer;
  81959. })(BABYLON || (BABYLON = {}));
  81960. //# sourceMappingURL=babylon.sceneSerializer.js.map
  81961. var BABYLON;
  81962. (function (BABYLON) {
  81963. var ReflectionProbe = /** @class */ (function () {
  81964. function ReflectionProbe(name, size, scene, generateMipMaps) {
  81965. if (generateMipMaps === void 0) { generateMipMaps = true; }
  81966. var _this = this;
  81967. this.name = name;
  81968. this._viewMatrix = BABYLON.Matrix.Identity();
  81969. this._target = BABYLON.Vector3.Zero();
  81970. this._add = BABYLON.Vector3.Zero();
  81971. this.invertYAxis = false;
  81972. this.position = BABYLON.Vector3.Zero();
  81973. this._scene = scene;
  81974. this._scene.reflectionProbes.push(this);
  81975. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  81976. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  81977. switch (faceIndex) {
  81978. case 0:
  81979. _this._add.copyFromFloats(1, 0, 0);
  81980. break;
  81981. case 1:
  81982. _this._add.copyFromFloats(-1, 0, 0);
  81983. break;
  81984. case 2:
  81985. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  81986. break;
  81987. case 3:
  81988. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  81989. break;
  81990. case 4:
  81991. _this._add.copyFromFloats(0, 0, 1);
  81992. break;
  81993. case 5:
  81994. _this._add.copyFromFloats(0, 0, -1);
  81995. break;
  81996. }
  81997. if (_this._attachedMesh) {
  81998. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  81999. }
  82000. _this.position.addToRef(_this._add, _this._target);
  82001. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  82002. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  82003. scene._forcedViewPosition = _this.position;
  82004. });
  82005. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  82006. scene._forcedViewPosition = null;
  82007. scene.updateTransformMatrix(true);
  82008. });
  82009. if (scene.activeCamera) {
  82010. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82011. }
  82012. }
  82013. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  82014. get: function () {
  82015. return this._renderTargetTexture.samples;
  82016. },
  82017. set: function (value) {
  82018. this._renderTargetTexture.samples = value;
  82019. },
  82020. enumerable: true,
  82021. configurable: true
  82022. });
  82023. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  82024. get: function () {
  82025. return this._renderTargetTexture.refreshRate;
  82026. },
  82027. set: function (value) {
  82028. this._renderTargetTexture.refreshRate = value;
  82029. },
  82030. enumerable: true,
  82031. configurable: true
  82032. });
  82033. ReflectionProbe.prototype.getScene = function () {
  82034. return this._scene;
  82035. };
  82036. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  82037. get: function () {
  82038. return this._renderTargetTexture;
  82039. },
  82040. enumerable: true,
  82041. configurable: true
  82042. });
  82043. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  82044. get: function () {
  82045. return this._renderTargetTexture.renderList;
  82046. },
  82047. enumerable: true,
  82048. configurable: true
  82049. });
  82050. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  82051. this._attachedMesh = mesh;
  82052. };
  82053. /**
  82054. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  82055. *
  82056. * @param renderingGroupId The rendering group id corresponding to its index
  82057. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  82058. */
  82059. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  82060. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  82061. };
  82062. ReflectionProbe.prototype.dispose = function () {
  82063. var index = this._scene.reflectionProbes.indexOf(this);
  82064. if (index !== -1) {
  82065. // Remove from the scene if found
  82066. this._scene.reflectionProbes.splice(index, 1);
  82067. }
  82068. if (this._renderTargetTexture) {
  82069. this._renderTargetTexture.dispose();
  82070. this._renderTargetTexture = null;
  82071. }
  82072. };
  82073. return ReflectionProbe;
  82074. }());
  82075. BABYLON.ReflectionProbe = ReflectionProbe;
  82076. })(BABYLON || (BABYLON = {}));
  82077. //# sourceMappingURL=babylon.reflectionProbe.js.map
  82078. var BABYLON;
  82079. (function (BABYLON) {
  82080. var Layer = /** @class */ (function () {
  82081. function Layer(name, imgUrl, scene, isBackground, color) {
  82082. this.name = name;
  82083. this.scale = new BABYLON.Vector2(1, 1);
  82084. this.offset = new BABYLON.Vector2(0, 0);
  82085. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  82086. this.layerMask = 0x0FFFFFFF;
  82087. this._vertexBuffers = {};
  82088. // Events
  82089. /**
  82090. * An event triggered when the layer is disposed.
  82091. * @type {BABYLON.Observable}
  82092. */
  82093. this.onDisposeObservable = new BABYLON.Observable();
  82094. /**
  82095. * An event triggered before rendering the scene
  82096. * @type {BABYLON.Observable}
  82097. */
  82098. this.onBeforeRenderObservable = new BABYLON.Observable();
  82099. /**
  82100. * An event triggered after rendering the scene
  82101. * @type {BABYLON.Observable}
  82102. */
  82103. this.onAfterRenderObservable = new BABYLON.Observable();
  82104. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  82105. this.isBackground = isBackground === undefined ? true : isBackground;
  82106. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  82107. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  82108. this._scene.layers.push(this);
  82109. var engine = this._scene.getEngine();
  82110. // VBO
  82111. var vertices = [];
  82112. vertices.push(1, 1);
  82113. vertices.push(-1, 1);
  82114. vertices.push(-1, -1);
  82115. vertices.push(1, -1);
  82116. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82117. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82118. this._createIndexBuffer();
  82119. // Effects
  82120. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  82121. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  82122. }
  82123. Object.defineProperty(Layer.prototype, "onDispose", {
  82124. set: function (callback) {
  82125. if (this._onDisposeObserver) {
  82126. this.onDisposeObservable.remove(this._onDisposeObserver);
  82127. }
  82128. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  82129. },
  82130. enumerable: true,
  82131. configurable: true
  82132. });
  82133. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  82134. set: function (callback) {
  82135. if (this._onBeforeRenderObserver) {
  82136. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  82137. }
  82138. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  82139. },
  82140. enumerable: true,
  82141. configurable: true
  82142. });
  82143. Object.defineProperty(Layer.prototype, "onAfterRender", {
  82144. set: function (callback) {
  82145. if (this._onAfterRenderObserver) {
  82146. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82147. }
  82148. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  82149. },
  82150. enumerable: true,
  82151. configurable: true
  82152. });
  82153. Layer.prototype._createIndexBuffer = function () {
  82154. var engine = this._scene.getEngine();
  82155. // Indices
  82156. var indices = [];
  82157. indices.push(0);
  82158. indices.push(1);
  82159. indices.push(2);
  82160. indices.push(0);
  82161. indices.push(2);
  82162. indices.push(3);
  82163. this._indexBuffer = engine.createIndexBuffer(indices);
  82164. };
  82165. Layer.prototype._rebuild = function () {
  82166. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82167. if (vb) {
  82168. vb._rebuild();
  82169. }
  82170. this._createIndexBuffer();
  82171. };
  82172. Layer.prototype.render = function () {
  82173. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  82174. // Check
  82175. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  82176. return;
  82177. var engine = this._scene.getEngine();
  82178. this.onBeforeRenderObservable.notifyObservers(this);
  82179. // Render
  82180. engine.enableEffect(currentEffect);
  82181. engine.setState(false);
  82182. // Texture
  82183. currentEffect.setTexture("textureSampler", this.texture);
  82184. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  82185. // Color
  82186. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  82187. // Scale / offset
  82188. currentEffect.setVector2("offset", this.offset);
  82189. currentEffect.setVector2("scale", this.scale);
  82190. // VBOs
  82191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82192. // Draw order
  82193. if (!this.alphaTest) {
  82194. engine.setAlphaMode(this.alphaBlendingMode);
  82195. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82196. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82197. }
  82198. else {
  82199. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82200. }
  82201. this.onAfterRenderObservable.notifyObservers(this);
  82202. };
  82203. Layer.prototype.dispose = function () {
  82204. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82205. if (vertexBuffer) {
  82206. vertexBuffer.dispose();
  82207. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82208. }
  82209. if (this._indexBuffer) {
  82210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82211. this._indexBuffer = null;
  82212. }
  82213. if (this.texture) {
  82214. this.texture.dispose();
  82215. this.texture = null;
  82216. }
  82217. // Remove from scene
  82218. var index = this._scene.layers.indexOf(this);
  82219. this._scene.layers.splice(index, 1);
  82220. // Callback
  82221. this.onDisposeObservable.notifyObservers(this);
  82222. this.onDisposeObservable.clear();
  82223. this.onAfterRenderObservable.clear();
  82224. this.onBeforeRenderObservable.clear();
  82225. };
  82226. return Layer;
  82227. }());
  82228. BABYLON.Layer = Layer;
  82229. })(BABYLON || (BABYLON = {}));
  82230. //# sourceMappingURL=babylon.layer.js.map
  82231. var BABYLON;
  82232. (function (BABYLON) {
  82233. var TextureTools = /** @class */ (function () {
  82234. function TextureTools() {
  82235. }
  82236. /**
  82237. * Uses the GPU to create a copy texture rescaled at a given size
  82238. * @param texture Texture to copy from
  82239. * @param width Desired width
  82240. * @param height Desired height
  82241. * @return Generated texture
  82242. */
  82243. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  82244. if (useBilinearMode === void 0) { useBilinearMode = true; }
  82245. var scene = texture.getScene();
  82246. var engine = scene.getEngine();
  82247. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  82248. rtt.wrapU = texture.wrapU;
  82249. rtt.wrapV = texture.wrapV;
  82250. rtt.uOffset = texture.uOffset;
  82251. rtt.vOffset = texture.vOffset;
  82252. rtt.uScale = texture.uScale;
  82253. rtt.vScale = texture.vScale;
  82254. rtt.uAng = texture.uAng;
  82255. rtt.vAng = texture.vAng;
  82256. rtt.wAng = texture.wAng;
  82257. rtt.coordinatesIndex = texture.coordinatesIndex;
  82258. rtt.level = texture.level;
  82259. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  82260. rtt._texture.isReady = false;
  82261. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82262. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82263. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82264. passPostProcess.getEffect().executeWhenCompiled(function () {
  82265. passPostProcess.onApply = function (effect) {
  82266. effect.setTexture("textureSampler", texture);
  82267. };
  82268. var internalTexture = rtt.getInternalTexture();
  82269. if (internalTexture) {
  82270. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  82271. engine.unBindFramebuffer(internalTexture);
  82272. rtt.disposeFramebufferObjects();
  82273. passPostProcess.dispose();
  82274. internalTexture.isReady = true;
  82275. }
  82276. });
  82277. return rtt;
  82278. };
  82279. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  82280. if (!scene._environmentBRDFTexture) {
  82281. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82282. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82283. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82284. scene._environmentBRDFTexture = texture;
  82285. }
  82286. return scene._environmentBRDFTexture;
  82287. };
  82288. 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=";
  82289. return TextureTools;
  82290. }());
  82291. BABYLON.TextureTools = TextureTools;
  82292. })(BABYLON || (BABYLON = {}));
  82293. //# sourceMappingURL=babylon.textureTools.js.map
  82294. var BABYLON;
  82295. (function (BABYLON) {
  82296. var FramingBehavior = /** @class */ (function () {
  82297. function FramingBehavior() {
  82298. this._mode = FramingBehavior.FitFrustumSidesMode;
  82299. this._radiusScale = 1.0;
  82300. this._positionScale = 0.5;
  82301. this._defaultElevation = 0.3;
  82302. this._elevationReturnTime = 1500;
  82303. this._elevationReturnWaitTime = 1000;
  82304. this._zoomStopsAnimation = false;
  82305. this._framingTime = 1500;
  82306. this._isPointerDown = false;
  82307. this._lastInteractionTime = -Infinity;
  82308. // Framing control
  82309. this._animatables = new Array();
  82310. this._betaIsAnimating = false;
  82311. }
  82312. Object.defineProperty(FramingBehavior.prototype, "name", {
  82313. get: function () {
  82314. return "Framing";
  82315. },
  82316. enumerable: true,
  82317. configurable: true
  82318. });
  82319. Object.defineProperty(FramingBehavior.prototype, "mode", {
  82320. /**
  82321. * Gets current mode used by the behavior.
  82322. */
  82323. get: function () {
  82324. return this._mode;
  82325. },
  82326. /**
  82327. * Sets the current mode used by the behavior
  82328. */
  82329. set: function (mode) {
  82330. this._mode = mode;
  82331. },
  82332. enumerable: true,
  82333. configurable: true
  82334. });
  82335. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  82336. /**
  82337. * Gets the scale applied to the radius
  82338. */
  82339. get: function () {
  82340. return this._radiusScale;
  82341. },
  82342. /**
  82343. * Sets the scale applied to the radius (1 by default)
  82344. */
  82345. set: function (radius) {
  82346. this._radiusScale = radius;
  82347. },
  82348. enumerable: true,
  82349. configurable: true
  82350. });
  82351. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  82352. /**
  82353. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82354. */
  82355. get: function () {
  82356. return this._positionScale;
  82357. },
  82358. /**
  82359. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82360. */
  82361. set: function (scale) {
  82362. this._positionScale = scale;
  82363. },
  82364. enumerable: true,
  82365. configurable: true
  82366. });
  82367. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  82368. /**
  82369. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82370. * behaviour is triggered, in radians.
  82371. */
  82372. get: function () {
  82373. return this._defaultElevation;
  82374. },
  82375. /**
  82376. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82377. * behaviour is triggered, in radians.
  82378. */
  82379. set: function (elevation) {
  82380. this._defaultElevation = elevation;
  82381. },
  82382. enumerable: true,
  82383. configurable: true
  82384. });
  82385. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  82386. /**
  82387. * Gets the time (in milliseconds) taken to return to the default beta position.
  82388. * Negative value indicates camera should not return to default.
  82389. */
  82390. get: function () {
  82391. return this._elevationReturnTime;
  82392. },
  82393. /**
  82394. * Sets the time (in milliseconds) taken to return to the default beta position.
  82395. * Negative value indicates camera should not return to default.
  82396. */
  82397. set: function (speed) {
  82398. this._elevationReturnTime = speed;
  82399. },
  82400. enumerable: true,
  82401. configurable: true
  82402. });
  82403. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  82404. /**
  82405. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82406. */
  82407. get: function () {
  82408. return this._elevationReturnWaitTime;
  82409. },
  82410. /**
  82411. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82412. */
  82413. set: function (time) {
  82414. this._elevationReturnWaitTime = time;
  82415. },
  82416. enumerable: true,
  82417. configurable: true
  82418. });
  82419. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  82420. /**
  82421. * Gets the flag that indicates if user zooming should stop animation.
  82422. */
  82423. get: function () {
  82424. return this._zoomStopsAnimation;
  82425. },
  82426. /**
  82427. * Sets the flag that indicates if user zooming should stop animation.
  82428. */
  82429. set: function (flag) {
  82430. this._zoomStopsAnimation = flag;
  82431. },
  82432. enumerable: true,
  82433. configurable: true
  82434. });
  82435. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  82436. /**
  82437. * Gets the transition time when framing the mesh, in milliseconds
  82438. */
  82439. get: function () {
  82440. return this._framingTime;
  82441. },
  82442. /**
  82443. * Sets the transition time when framing the mesh, in milliseconds
  82444. */
  82445. set: function (time) {
  82446. this._framingTime = time;
  82447. },
  82448. enumerable: true,
  82449. configurable: true
  82450. });
  82451. FramingBehavior.prototype.init = function () {
  82452. // Do notihng
  82453. };
  82454. FramingBehavior.prototype.attach = function (camera) {
  82455. var _this = this;
  82456. this._attachedCamera = camera;
  82457. var scene = this._attachedCamera.getScene();
  82458. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  82459. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82460. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82461. _this._isPointerDown = true;
  82462. return;
  82463. }
  82464. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82465. _this._isPointerDown = false;
  82466. }
  82467. });
  82468. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82469. if (mesh) {
  82470. _this.zoomOnMesh(mesh);
  82471. }
  82472. });
  82473. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82474. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82475. _this._applyUserInteraction();
  82476. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  82477. // back to the default position after a given timeout
  82478. _this._maintainCameraAboveGround();
  82479. });
  82480. };
  82481. FramingBehavior.prototype.detach = function () {
  82482. if (!this._attachedCamera) {
  82483. return;
  82484. }
  82485. var scene = this._attachedCamera.getScene();
  82486. if (this._onPrePointerObservableObserver) {
  82487. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82488. }
  82489. if (this._onAfterCheckInputsObserver) {
  82490. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82491. }
  82492. if (this._onMeshTargetChangedObserver) {
  82493. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82494. }
  82495. this._attachedCamera = null;
  82496. };
  82497. /**
  82498. * Targets the given mesh and updates zoom level accordingly.
  82499. * @param mesh The mesh to target.
  82500. * @param radius Optional. If a cached radius position already exists, overrides default.
  82501. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82502. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82503. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82504. */
  82505. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82506. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82507. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82508. mesh.computeWorldMatrix(true);
  82509. var boundingBox = mesh.getBoundingInfo().boundingBox;
  82510. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  82511. };
  82512. /**
  82513. * Targets the given mesh with its children and updates zoom level accordingly.
  82514. * @param mesh The mesh to target.
  82515. * @param radius Optional. If a cached radius position already exists, overrides default.
  82516. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82517. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82518. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82519. */
  82520. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82521. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82522. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82523. mesh.computeWorldMatrix(true);
  82524. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  82525. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  82526. };
  82527. /**
  82528. * Targets the given meshes with their children and updates zoom level accordingly.
  82529. * @param meshes The mesh to target.
  82530. * @param radius Optional. If a cached radius position already exists, overrides default.
  82531. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82532. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82533. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82534. */
  82535. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  82536. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82537. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82538. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  82539. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82540. for (var i = 0; i < meshes.length; i++) {
  82541. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  82542. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  82543. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  82544. }
  82545. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  82546. };
  82547. /**
  82548. * Targets the given mesh and updates zoom level accordingly.
  82549. * @param mesh The mesh to target.
  82550. * @param radius Optional. If a cached radius position already exists, overrides default.
  82551. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82552. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82553. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82554. */
  82555. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  82556. var _this = this;
  82557. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82558. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82559. var zoomTarget;
  82560. if (!this._attachedCamera) {
  82561. return;
  82562. }
  82563. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  82564. var bottom = minimumWorld.y;
  82565. var top = maximumWorld.y;
  82566. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  82567. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  82568. if (focusOnOriginXZ) {
  82569. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  82570. }
  82571. else {
  82572. var centerWorld = minimumWorld.add(radiusWorld);
  82573. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  82574. }
  82575. if (!this._vectorTransition) {
  82576. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  82577. }
  82578. this._betaIsAnimating = true;
  82579. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  82580. if (animatable) {
  82581. this._animatables.push(animatable);
  82582. }
  82583. // sets the radius and lower radius bounds
  82584. // Small delta ensures camera is not always at lower zoom limit.
  82585. var radius = 0;
  82586. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  82587. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82588. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  82589. radius = position;
  82590. }
  82591. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82592. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82593. if (this._attachedCamera.lowerRadiusLimit === null) {
  82594. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  82595. }
  82596. }
  82597. // Set sensibilities
  82598. var extend = maximumWorld.subtract(minimumWorld).length();
  82599. this._attachedCamera.panningSensibility = 5000 / extend;
  82600. this._attachedCamera.wheelPrecision = 100 / radius;
  82601. // transition to new radius
  82602. if (!this._radiusTransition) {
  82603. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82604. }
  82605. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  82606. if (onAnimationEnd) {
  82607. onAnimationEnd();
  82608. }
  82609. if (_this._attachedCamera) {
  82610. _this._attachedCamera.storeState();
  82611. }
  82612. });
  82613. if (animatable) {
  82614. this._animatables.push(animatable);
  82615. }
  82616. };
  82617. /**
  82618. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  82619. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  82620. * frustum width.
  82621. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  82622. * to fully enclose the mesh in the viewing frustum.
  82623. */
  82624. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  82625. var size = maximumWorld.subtract(minimumWorld);
  82626. var boxVectorGlobalDiagonal = size.length();
  82627. var frustumSlope = this._getFrustumSlope();
  82628. // Formula for setting distance
  82629. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  82630. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  82631. // Horizon distance
  82632. var radius = radiusWithoutFraming * this._radiusScale;
  82633. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  82634. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  82635. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  82636. var camera = this._attachedCamera;
  82637. if (!camera) {
  82638. return 0;
  82639. }
  82640. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82641. // Don't exceed the requested limit
  82642. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  82643. }
  82644. // Don't exceed the upper radius limit
  82645. if (camera.upperRadiusLimit) {
  82646. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  82647. }
  82648. return distance;
  82649. };
  82650. /**
  82651. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  82652. * is automatically returned to its default position (expected to be above ground plane).
  82653. */
  82654. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  82655. var _this = this;
  82656. if (this._elevationReturnTime < 0) {
  82657. return;
  82658. }
  82659. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  82660. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  82661. var limitBeta = Math.PI * 0.5;
  82662. // Bring the camera back up if below the ground plane
  82663. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  82664. this._betaIsAnimating = true;
  82665. //Transition to new position
  82666. this.stopAllAnimations();
  82667. if (!this._betaTransition) {
  82668. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82669. }
  82670. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  82671. _this._clearAnimationLocks();
  82672. _this.stopAllAnimations();
  82673. });
  82674. if (animatabe) {
  82675. this._animatables.push(animatabe);
  82676. }
  82677. }
  82678. };
  82679. /**
  82680. * Returns the frustum slope based on the canvas ratio and camera FOV
  82681. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  82682. */
  82683. FramingBehavior.prototype._getFrustumSlope = function () {
  82684. // Calculate the viewport ratio
  82685. // Aspect Ratio is Height/Width.
  82686. var camera = this._attachedCamera;
  82687. if (!camera) {
  82688. return BABYLON.Vector2.Zero();
  82689. }
  82690. var engine = camera.getScene().getEngine();
  82691. var aspectRatio = engine.getAspectRatio(camera);
  82692. // Camera FOV is the vertical field of view (top-bottom) in radians.
  82693. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  82694. var frustumSlopeY = Math.tan(camera.fov / 2);
  82695. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  82696. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  82697. // along the forward vector.
  82698. var frustumSlopeX = frustumSlopeY * aspectRatio;
  82699. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  82700. };
  82701. /**
  82702. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  82703. */
  82704. FramingBehavior.prototype._clearAnimationLocks = function () {
  82705. this._betaIsAnimating = false;
  82706. };
  82707. /**
  82708. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82709. */
  82710. FramingBehavior.prototype._applyUserInteraction = function () {
  82711. if (this.isUserIsMoving) {
  82712. this._lastInteractionTime = BABYLON.Tools.Now;
  82713. this.stopAllAnimations();
  82714. this._clearAnimationLocks();
  82715. }
  82716. };
  82717. /**
  82718. * Stops and removes all animations that have been applied to the camera
  82719. */
  82720. FramingBehavior.prototype.stopAllAnimations = function () {
  82721. if (this._attachedCamera) {
  82722. this._attachedCamera.animations = [];
  82723. }
  82724. while (this._animatables.length) {
  82725. if (this._animatables[0]) {
  82726. this._animatables[0].onAnimationEnd = null;
  82727. this._animatables[0].stop();
  82728. }
  82729. this._animatables.shift();
  82730. }
  82731. };
  82732. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  82733. /**
  82734. * Gets a value indicating if the user is moving the camera
  82735. */
  82736. get: function () {
  82737. if (!this._attachedCamera) {
  82738. return false;
  82739. }
  82740. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82741. this._attachedCamera.inertialBetaOffset !== 0 ||
  82742. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82743. this._attachedCamera.inertialPanningX !== 0 ||
  82744. this._attachedCamera.inertialPanningY !== 0 ||
  82745. this._isPointerDown;
  82746. },
  82747. enumerable: true,
  82748. configurable: true
  82749. });
  82750. /**
  82751. * The easing function used by animations
  82752. */
  82753. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  82754. /**
  82755. * The easing mode used by animations
  82756. */
  82757. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  82758. // Statics
  82759. /**
  82760. * The camera can move all the way towards the mesh.
  82761. */
  82762. FramingBehavior.IgnoreBoundsSizeMode = 0;
  82763. /**
  82764. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  82765. */
  82766. FramingBehavior.FitFrustumSidesMode = 1;
  82767. return FramingBehavior;
  82768. }());
  82769. BABYLON.FramingBehavior = FramingBehavior;
  82770. })(BABYLON || (BABYLON = {}));
  82771. //# sourceMappingURL=babylon.framingBehavior.js.map
  82772. var BABYLON;
  82773. (function (BABYLON) {
  82774. /**
  82775. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  82776. */
  82777. var BouncingBehavior = /** @class */ (function () {
  82778. function BouncingBehavior() {
  82779. /**
  82780. * The duration of the animation, in milliseconds
  82781. */
  82782. this.transitionDuration = 450;
  82783. /**
  82784. * Length of the distance animated by the transition when lower radius is reached
  82785. */
  82786. this.lowerRadiusTransitionRange = 2;
  82787. /**
  82788. * Length of the distance animated by the transition when upper radius is reached
  82789. */
  82790. this.upperRadiusTransitionRange = -2;
  82791. this._autoTransitionRange = false;
  82792. // Animations
  82793. this._radiusIsAnimating = false;
  82794. this._radiusBounceTransition = null;
  82795. this._animatables = new Array();
  82796. }
  82797. Object.defineProperty(BouncingBehavior.prototype, "name", {
  82798. get: function () {
  82799. return "Bouncing";
  82800. },
  82801. enumerable: true,
  82802. configurable: true
  82803. });
  82804. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  82805. /**
  82806. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82807. */
  82808. get: function () {
  82809. return this._autoTransitionRange;
  82810. },
  82811. /**
  82812. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82813. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  82814. */
  82815. set: function (value) {
  82816. var _this = this;
  82817. if (this._autoTransitionRange === value) {
  82818. return;
  82819. }
  82820. this._autoTransitionRange = value;
  82821. var camera = this._attachedCamera;
  82822. if (!camera) {
  82823. return;
  82824. }
  82825. if (value) {
  82826. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82827. if (!mesh) {
  82828. return;
  82829. }
  82830. mesh.computeWorldMatrix(true);
  82831. var diagonal = mesh.getBoundingInfo().diagonalLength;
  82832. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  82833. _this.upperRadiusTransitionRange = diagonal * 0.05;
  82834. });
  82835. }
  82836. else if (this._onMeshTargetChangedObserver) {
  82837. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82838. }
  82839. },
  82840. enumerable: true,
  82841. configurable: true
  82842. });
  82843. BouncingBehavior.prototype.init = function () {
  82844. // Do notihng
  82845. };
  82846. BouncingBehavior.prototype.attach = function (camera) {
  82847. var _this = this;
  82848. this._attachedCamera = camera;
  82849. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82850. if (!_this._attachedCamera) {
  82851. return;
  82852. }
  82853. // Add the bounce animation to the lower radius limit
  82854. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  82855. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  82856. }
  82857. // Add the bounce animation to the upper radius limit
  82858. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  82859. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  82860. }
  82861. });
  82862. };
  82863. BouncingBehavior.prototype.detach = function () {
  82864. if (!this._attachedCamera) {
  82865. return;
  82866. }
  82867. if (this._onAfterCheckInputsObserver) {
  82868. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82869. }
  82870. if (this._onMeshTargetChangedObserver) {
  82871. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82872. }
  82873. this._attachedCamera = null;
  82874. };
  82875. /**
  82876. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  82877. * @param radiusLimit The limit to check against.
  82878. * @return Bool to indicate if at limit.
  82879. */
  82880. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  82881. if (!this._attachedCamera) {
  82882. return false;
  82883. }
  82884. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  82885. return true;
  82886. }
  82887. return false;
  82888. };
  82889. /**
  82890. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  82891. * @param radiusDelta The delta by which to animate to. Can be negative.
  82892. */
  82893. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  82894. var _this = this;
  82895. if (!this._attachedCamera) {
  82896. return;
  82897. }
  82898. if (!this._radiusBounceTransition) {
  82899. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  82900. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  82901. }
  82902. // Prevent zoom until bounce has completed
  82903. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  82904. this._attachedCamera.wheelPrecision = Infinity;
  82905. this._attachedCamera.inertialRadiusOffset = 0;
  82906. // Animate to the radius limit
  82907. this.stopAllAnimations();
  82908. this._radiusIsAnimating = true;
  82909. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  82910. if (animatable) {
  82911. this._animatables.push(animatable);
  82912. }
  82913. };
  82914. /**
  82915. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  82916. */
  82917. BouncingBehavior.prototype._clearAnimationLocks = function () {
  82918. this._radiusIsAnimating = false;
  82919. if (this._attachedCamera) {
  82920. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  82921. }
  82922. };
  82923. /**
  82924. * Stops and removes all animations that have been applied to the camera
  82925. */
  82926. BouncingBehavior.prototype.stopAllAnimations = function () {
  82927. if (this._attachedCamera) {
  82928. this._attachedCamera.animations = [];
  82929. }
  82930. while (this._animatables.length) {
  82931. this._animatables[0].onAnimationEnd = null;
  82932. this._animatables[0].stop();
  82933. this._animatables.shift();
  82934. }
  82935. };
  82936. /**
  82937. * The easing function used by animations
  82938. */
  82939. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  82940. /**
  82941. * The easing mode used by animations
  82942. */
  82943. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  82944. return BouncingBehavior;
  82945. }());
  82946. BABYLON.BouncingBehavior = BouncingBehavior;
  82947. })(BABYLON || (BABYLON = {}));
  82948. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  82949. var BABYLON;
  82950. (function (BABYLON) {
  82951. var AutoRotationBehavior = /** @class */ (function () {
  82952. function AutoRotationBehavior() {
  82953. this._zoomStopsAnimation = false;
  82954. this._idleRotationSpeed = 0.05;
  82955. this._idleRotationWaitTime = 2000;
  82956. this._idleRotationSpinupTime = 2000;
  82957. this._isPointerDown = false;
  82958. this._lastFrameTime = null;
  82959. this._lastInteractionTime = -Infinity;
  82960. this._cameraRotationSpeed = 0;
  82961. this._lastFrameRadius = 0;
  82962. }
  82963. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  82964. get: function () {
  82965. return "AutoRotation";
  82966. },
  82967. enumerable: true,
  82968. configurable: true
  82969. });
  82970. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  82971. /**
  82972. * Gets the flag that indicates if user zooming should stop animation.
  82973. */
  82974. get: function () {
  82975. return this._zoomStopsAnimation;
  82976. },
  82977. /**
  82978. * Sets the flag that indicates if user zooming should stop animation.
  82979. */
  82980. set: function (flag) {
  82981. this._zoomStopsAnimation = flag;
  82982. },
  82983. enumerable: true,
  82984. configurable: true
  82985. });
  82986. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  82987. /**
  82988. * Gets the default speed at which the camera rotates around the model.
  82989. */
  82990. get: function () {
  82991. return this._idleRotationSpeed;
  82992. },
  82993. /**
  82994. * Sets the default speed at which the camera rotates around the model.
  82995. */
  82996. set: function (speed) {
  82997. this._idleRotationSpeed = speed;
  82998. },
  82999. enumerable: true,
  83000. configurable: true
  83001. });
  83002. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  83003. /**
  83004. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  83005. */
  83006. get: function () {
  83007. return this._idleRotationWaitTime;
  83008. },
  83009. /**
  83010. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  83011. */
  83012. set: function (time) {
  83013. this._idleRotationWaitTime = time;
  83014. },
  83015. enumerable: true,
  83016. configurable: true
  83017. });
  83018. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  83019. /**
  83020. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83021. */
  83022. get: function () {
  83023. return this._idleRotationSpinupTime;
  83024. },
  83025. /**
  83026. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83027. */
  83028. set: function (time) {
  83029. this._idleRotationSpinupTime = time;
  83030. },
  83031. enumerable: true,
  83032. configurable: true
  83033. });
  83034. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  83035. /**
  83036. * Gets a value indicating if the camera is currently rotating because of this behavior
  83037. */
  83038. get: function () {
  83039. return Math.abs(this._cameraRotationSpeed) > 0;
  83040. },
  83041. enumerable: true,
  83042. configurable: true
  83043. });
  83044. AutoRotationBehavior.prototype.init = function () {
  83045. // Do notihng
  83046. };
  83047. AutoRotationBehavior.prototype.attach = function (camera) {
  83048. var _this = this;
  83049. this._attachedCamera = camera;
  83050. var scene = this._attachedCamera.getScene();
  83051. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  83052. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  83053. _this._isPointerDown = true;
  83054. return;
  83055. }
  83056. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  83057. _this._isPointerDown = false;
  83058. }
  83059. });
  83060. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83061. var now = BABYLON.Tools.Now;
  83062. var dt = 0;
  83063. if (_this._lastFrameTime != null) {
  83064. dt = now - _this._lastFrameTime;
  83065. }
  83066. _this._lastFrameTime = now;
  83067. // Stop the animation if there is user interaction and the animation should stop for this interaction
  83068. _this._applyUserInteraction();
  83069. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  83070. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  83071. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  83072. // Step camera rotation by rotation speed
  83073. if (_this._attachedCamera) {
  83074. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  83075. }
  83076. });
  83077. };
  83078. AutoRotationBehavior.prototype.detach = function () {
  83079. if (!this._attachedCamera) {
  83080. return;
  83081. }
  83082. var scene = this._attachedCamera.getScene();
  83083. if (this._onPrePointerObservableObserver) {
  83084. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  83085. }
  83086. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83087. this._attachedCamera = null;
  83088. };
  83089. /**
  83090. * Returns true if user is scrolling.
  83091. * @return true if user is scrolling.
  83092. */
  83093. AutoRotationBehavior.prototype._userIsZooming = function () {
  83094. if (!this._attachedCamera) {
  83095. return false;
  83096. }
  83097. return this._attachedCamera.inertialRadiusOffset !== 0;
  83098. };
  83099. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  83100. if (!this._attachedCamera) {
  83101. return false;
  83102. }
  83103. var zoomHasHitLimit = false;
  83104. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  83105. zoomHasHitLimit = true;
  83106. }
  83107. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  83108. this._lastFrameRadius = this._attachedCamera.radius;
  83109. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  83110. };
  83111. /**
  83112. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  83113. */
  83114. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  83115. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  83116. this._lastInteractionTime = BABYLON.Tools.Now;
  83117. }
  83118. };
  83119. // Tools
  83120. AutoRotationBehavior.prototype._userIsMoving = function () {
  83121. if (!this._attachedCamera) {
  83122. return false;
  83123. }
  83124. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  83125. this._attachedCamera.inertialBetaOffset !== 0 ||
  83126. this._attachedCamera.inertialRadiusOffset !== 0 ||
  83127. this._attachedCamera.inertialPanningX !== 0 ||
  83128. this._attachedCamera.inertialPanningY !== 0 ||
  83129. this._isPointerDown;
  83130. };
  83131. return AutoRotationBehavior;
  83132. }());
  83133. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  83134. })(BABYLON || (BABYLON = {}));
  83135. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  83136. var BABYLON;
  83137. (function (BABYLON) {
  83138. var NullEngineOptions = /** @class */ (function () {
  83139. function NullEngineOptions() {
  83140. this.renderWidth = 512;
  83141. this.renderHeight = 256;
  83142. this.textureSize = 512;
  83143. this.deterministicLockstep = false;
  83144. this.lockstepMaxSteps = 4;
  83145. }
  83146. return NullEngineOptions;
  83147. }());
  83148. BABYLON.NullEngineOptions = NullEngineOptions;
  83149. /**
  83150. * The null engine class provides support for headless version of babylon.js.
  83151. * This can be used in server side scenario or for testing purposes
  83152. */
  83153. var NullEngine = /** @class */ (function (_super) {
  83154. __extends(NullEngine, _super);
  83155. function NullEngine(options) {
  83156. if (options === void 0) { options = new NullEngineOptions(); }
  83157. var _this = _super.call(this, null) || this;
  83158. if (options.deterministicLockstep === undefined) {
  83159. options.deterministicLockstep = false;
  83160. }
  83161. if (options.lockstepMaxSteps === undefined) {
  83162. options.lockstepMaxSteps = 4;
  83163. }
  83164. _this._options = options;
  83165. // Init caps
  83166. // We consider we are on a webgl1 capable device
  83167. _this._caps = new BABYLON.EngineCapabilities();
  83168. _this._caps.maxTexturesImageUnits = 16;
  83169. _this._caps.maxVertexTextureImageUnits = 16;
  83170. _this._caps.maxTextureSize = 512;
  83171. _this._caps.maxCubemapTextureSize = 512;
  83172. _this._caps.maxRenderTextureSize = 512;
  83173. _this._caps.maxVertexAttribs = 16;
  83174. _this._caps.maxVaryingVectors = 16;
  83175. _this._caps.maxFragmentUniformVectors = 16;
  83176. _this._caps.maxVertexUniformVectors = 16;
  83177. // Extensions
  83178. _this._caps.standardDerivatives = false;
  83179. _this._caps.astc = null;
  83180. _this._caps.s3tc = null;
  83181. _this._caps.pvrtc = null;
  83182. _this._caps.etc1 = null;
  83183. _this._caps.etc2 = null;
  83184. _this._caps.textureAnisotropicFilterExtension = null;
  83185. _this._caps.maxAnisotropy = 0;
  83186. _this._caps.uintIndices = false;
  83187. _this._caps.fragmentDepthSupported = false;
  83188. _this._caps.highPrecisionShaderSupported = true;
  83189. _this._caps.colorBufferFloat = false;
  83190. _this._caps.textureFloat = false;
  83191. _this._caps.textureFloatLinearFiltering = false;
  83192. _this._caps.textureFloatRender = false;
  83193. _this._caps.textureHalfFloat = false;
  83194. _this._caps.textureHalfFloatLinearFiltering = false;
  83195. _this._caps.textureHalfFloatRender = false;
  83196. _this._caps.textureLOD = false;
  83197. _this._caps.drawBuffersExtension = false;
  83198. _this._caps.depthTextureExtension = false;
  83199. _this._caps.vertexArrayObject = false;
  83200. _this._caps.instancedArrays = false;
  83201. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  83202. // Wrappers
  83203. if (typeof URL === "undefined") {
  83204. URL = {
  83205. createObjectURL: function () { },
  83206. revokeObjectURL: function () { }
  83207. };
  83208. }
  83209. if (typeof Blob === "undefined") {
  83210. Blob = function () { };
  83211. }
  83212. return _this;
  83213. }
  83214. NullEngine.prototype.isDeterministicLockStep = function () {
  83215. return this._options.deterministicLockstep;
  83216. };
  83217. NullEngine.prototype.getLockstepMaxSteps = function () {
  83218. return this._options.lockstepMaxSteps;
  83219. };
  83220. NullEngine.prototype.createVertexBuffer = function (vertices) {
  83221. return {
  83222. capacity: 0,
  83223. references: 1,
  83224. is32Bits: false
  83225. };
  83226. };
  83227. NullEngine.prototype.createIndexBuffer = function (indices) {
  83228. return {
  83229. capacity: 0,
  83230. references: 1,
  83231. is32Bits: false
  83232. };
  83233. };
  83234. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  83235. if (stencil === void 0) { stencil = false; }
  83236. };
  83237. NullEngine.prototype.getRenderWidth = function (useScreen) {
  83238. if (useScreen === void 0) { useScreen = false; }
  83239. if (!useScreen && this._currentRenderTarget) {
  83240. return this._currentRenderTarget.width;
  83241. }
  83242. return this._options.renderWidth;
  83243. };
  83244. NullEngine.prototype.getRenderHeight = function (useScreen) {
  83245. if (useScreen === void 0) { useScreen = false; }
  83246. if (!useScreen && this._currentRenderTarget) {
  83247. return this._currentRenderTarget.height;
  83248. }
  83249. return this._options.renderHeight;
  83250. };
  83251. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  83252. this._cachedViewport = viewport;
  83253. };
  83254. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  83255. return {
  83256. transformFeedback: null,
  83257. __SPECTOR_rebuildProgram: null
  83258. };
  83259. };
  83260. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  83261. return [];
  83262. };
  83263. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  83264. return [];
  83265. };
  83266. NullEngine.prototype.bindSamplers = function (effect) {
  83267. this._currentEffect = null;
  83268. };
  83269. NullEngine.prototype.enableEffect = function (effect) {
  83270. this._currentEffect = effect;
  83271. if (effect.onBind) {
  83272. effect.onBind(effect);
  83273. }
  83274. effect.onBindObservable.notifyObservers(effect);
  83275. };
  83276. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  83277. if (zOffset === void 0) { zOffset = 0; }
  83278. if (reverseSide === void 0) { reverseSide = false; }
  83279. };
  83280. NullEngine.prototype.setIntArray = function (uniform, array) {
  83281. };
  83282. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  83283. };
  83284. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  83285. };
  83286. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  83287. };
  83288. NullEngine.prototype.setFloatArray = function (uniform, array) {
  83289. };
  83290. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  83291. };
  83292. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  83293. };
  83294. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  83295. };
  83296. NullEngine.prototype.setArray = function (uniform, array) {
  83297. };
  83298. NullEngine.prototype.setArray2 = function (uniform, array) {
  83299. };
  83300. NullEngine.prototype.setArray3 = function (uniform, array) {
  83301. };
  83302. NullEngine.prototype.setArray4 = function (uniform, array) {
  83303. };
  83304. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  83305. };
  83306. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  83307. };
  83308. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  83309. };
  83310. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  83311. };
  83312. NullEngine.prototype.setFloat = function (uniform, value) {
  83313. };
  83314. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  83315. };
  83316. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  83317. };
  83318. NullEngine.prototype.setBool = function (uniform, bool) {
  83319. };
  83320. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  83321. };
  83322. NullEngine.prototype.setColor3 = function (uniform, color3) {
  83323. };
  83324. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  83325. };
  83326. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  83327. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  83328. if (this._alphaMode === mode) {
  83329. return;
  83330. }
  83331. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  83332. if (!noDepthWriteChange) {
  83333. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  83334. }
  83335. this._alphaMode = mode;
  83336. };
  83337. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  83338. };
  83339. NullEngine.prototype.wipeCaches = function (bruteForce) {
  83340. if (this.preventCacheWipeBetweenFrames) {
  83341. return;
  83342. }
  83343. this.resetTextureCache();
  83344. this._currentEffect = null;
  83345. if (bruteForce) {
  83346. this._currentProgram = null;
  83347. this._stencilState.reset();
  83348. this._depthCullingState.reset();
  83349. this.setDepthFunctionToLessOrEqual();
  83350. this._alphaState.reset();
  83351. }
  83352. this._cachedVertexBuffers = null;
  83353. this._cachedIndexBuffer = null;
  83354. this._cachedEffectForVertexBuffers = null;
  83355. };
  83356. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  83357. };
  83358. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  83359. };
  83360. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  83361. };
  83362. NullEngine.prototype._createTexture = function () {
  83363. return {};
  83364. };
  83365. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  83366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83367. if (onLoad === void 0) { onLoad = null; }
  83368. if (onError === void 0) { onError = null; }
  83369. if (buffer === void 0) { buffer = null; }
  83370. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  83371. var url = String(urlArg);
  83372. texture.url = url;
  83373. texture.generateMipMaps = !noMipmap;
  83374. texture.samplingMode = samplingMode;
  83375. texture.invertY = invertY;
  83376. texture.baseWidth = this._options.textureSize;
  83377. texture.baseHeight = this._options.textureSize;
  83378. texture.width = this._options.textureSize;
  83379. texture.height = this._options.textureSize;
  83380. if (format) {
  83381. texture.format = format;
  83382. }
  83383. texture.isReady = true;
  83384. if (onLoad) {
  83385. onLoad();
  83386. }
  83387. return texture;
  83388. };
  83389. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  83390. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  83391. if (options !== undefined && typeof options === "object") {
  83392. fullOptions.generateMipMaps = options.generateMipMaps;
  83393. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  83394. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  83395. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  83396. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  83397. }
  83398. else {
  83399. fullOptions.generateMipMaps = options;
  83400. fullOptions.generateDepthBuffer = true;
  83401. fullOptions.generateStencilBuffer = false;
  83402. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83403. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  83404. }
  83405. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  83406. var width = size.width || size;
  83407. var height = size.height || size;
  83408. texture._depthStencilBuffer = {};
  83409. texture._framebuffer = {};
  83410. texture.baseWidth = width;
  83411. texture.baseHeight = height;
  83412. texture.width = width;
  83413. texture.height = height;
  83414. texture.isReady = true;
  83415. texture.samples = 1;
  83416. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  83417. texture.samplingMode = fullOptions.samplingMode;
  83418. texture.type = fullOptions.type;
  83419. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  83420. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  83421. return texture;
  83422. };
  83423. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  83424. texture.samplingMode = samplingMode;
  83425. };
  83426. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  83427. if (this._currentRenderTarget) {
  83428. this.unBindFramebuffer(this._currentRenderTarget);
  83429. }
  83430. this._currentRenderTarget = texture;
  83431. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  83432. if (this._cachedViewport && !forceFullscreenViewport) {
  83433. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  83434. }
  83435. };
  83436. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  83437. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  83438. this._currentRenderTarget = null;
  83439. if (onBeforeUnbind) {
  83440. if (texture._MSAAFramebuffer) {
  83441. this._currentFramebuffer = texture._framebuffer;
  83442. }
  83443. onBeforeUnbind();
  83444. }
  83445. this._currentFramebuffer = null;
  83446. };
  83447. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  83448. var vbo = {
  83449. capacity: 1,
  83450. references: 1,
  83451. is32Bits: false
  83452. };
  83453. return vbo;
  83454. };
  83455. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  83456. if (offset === void 0) { offset = 0; }
  83457. };
  83458. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  83459. };
  83460. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  83461. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  83462. this._boundTexturesCache[this._activeChannel] = texture;
  83463. }
  83464. };
  83465. NullEngine.prototype._bindTexture = function (channel, texture) {
  83466. if (channel < 0) {
  83467. return;
  83468. }
  83469. this._bindTextureDirectly(0, texture);
  83470. };
  83471. NullEngine.prototype._releaseBuffer = function (buffer) {
  83472. buffer.references--;
  83473. if (buffer.references === 0) {
  83474. return true;
  83475. }
  83476. return false;
  83477. };
  83478. return NullEngine;
  83479. }(BABYLON.Engine));
  83480. BABYLON.NullEngine = NullEngine;
  83481. })(BABYLON || (BABYLON = {}));
  83482. //# sourceMappingURL=babylon.nullEngine.js.map
  83483. var BABYLON;
  83484. (function (BABYLON) {
  83485. /**
  83486. * This class can be used to get instrumentation data from a Babylon engine
  83487. */
  83488. var EngineInstrumentation = /** @class */ (function () {
  83489. function EngineInstrumentation(engine) {
  83490. this.engine = engine;
  83491. this._captureGPUFrameTime = false;
  83492. this._gpuFrameTime = new BABYLON.PerfCounter();
  83493. this._captureShaderCompilationTime = false;
  83494. this._shaderCompilationTime = new BABYLON.PerfCounter();
  83495. // Observers
  83496. this._onBeginFrameObserver = null;
  83497. this._onEndFrameObserver = null;
  83498. this._onBeforeShaderCompilationObserver = null;
  83499. this._onAfterShaderCompilationObserver = null;
  83500. }
  83501. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  83502. // Properties
  83503. /**
  83504. * Gets the perf counter used for GPU frame time
  83505. */
  83506. get: function () {
  83507. return this._gpuFrameTime;
  83508. },
  83509. enumerable: true,
  83510. configurable: true
  83511. });
  83512. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  83513. /**
  83514. * Gets the GPU frame time capture status
  83515. */
  83516. get: function () {
  83517. return this._captureGPUFrameTime;
  83518. },
  83519. /**
  83520. * Enable or disable the GPU frame time capture
  83521. */
  83522. set: function (value) {
  83523. var _this = this;
  83524. if (value === this._captureGPUFrameTime) {
  83525. return;
  83526. }
  83527. this._captureGPUFrameTime = value;
  83528. if (value) {
  83529. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  83530. if (!_this._gpuFrameTimeToken) {
  83531. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  83532. }
  83533. });
  83534. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  83535. if (!_this._gpuFrameTimeToken) {
  83536. return;
  83537. }
  83538. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  83539. if (time > -1) {
  83540. _this._gpuFrameTimeToken = null;
  83541. _this._gpuFrameTime.fetchNewFrame();
  83542. _this._gpuFrameTime.addCount(time, true);
  83543. }
  83544. });
  83545. }
  83546. else {
  83547. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83548. this._onBeginFrameObserver = null;
  83549. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83550. this._onEndFrameObserver = null;
  83551. }
  83552. },
  83553. enumerable: true,
  83554. configurable: true
  83555. });
  83556. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  83557. /**
  83558. * Gets the perf counter used for shader compilation time
  83559. */
  83560. get: function () {
  83561. return this._shaderCompilationTime;
  83562. },
  83563. enumerable: true,
  83564. configurable: true
  83565. });
  83566. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  83567. /**
  83568. * Gets the shader compilation time capture status
  83569. */
  83570. get: function () {
  83571. return this._captureShaderCompilationTime;
  83572. },
  83573. /**
  83574. * Enable or disable the shader compilation time capture
  83575. */
  83576. set: function (value) {
  83577. var _this = this;
  83578. if (value === this._captureShaderCompilationTime) {
  83579. return;
  83580. }
  83581. this._captureShaderCompilationTime = value;
  83582. if (value) {
  83583. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  83584. _this._shaderCompilationTime.fetchNewFrame();
  83585. _this._shaderCompilationTime.beginMonitoring();
  83586. });
  83587. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  83588. _this._shaderCompilationTime.endMonitoring();
  83589. });
  83590. }
  83591. else {
  83592. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83593. this._onBeforeShaderCompilationObserver = null;
  83594. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83595. this._onAfterShaderCompilationObserver = null;
  83596. }
  83597. },
  83598. enumerable: true,
  83599. configurable: true
  83600. });
  83601. EngineInstrumentation.prototype.dispose = function () {
  83602. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83603. this._onBeginFrameObserver = null;
  83604. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83605. this._onEndFrameObserver = null;
  83606. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83607. this._onBeforeShaderCompilationObserver = null;
  83608. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83609. this._onAfterShaderCompilationObserver = null;
  83610. this.engine = null;
  83611. };
  83612. return EngineInstrumentation;
  83613. }());
  83614. BABYLON.EngineInstrumentation = EngineInstrumentation;
  83615. })(BABYLON || (BABYLON = {}));
  83616. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  83617. var BABYLON;
  83618. (function (BABYLON) {
  83619. /**
  83620. * This class can be used to get instrumentation data from a Babylon engine
  83621. */
  83622. var SceneInstrumentation = /** @class */ (function () {
  83623. function SceneInstrumentation(scene) {
  83624. var _this = this;
  83625. this.scene = scene;
  83626. this._captureActiveMeshesEvaluationTime = false;
  83627. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  83628. this._captureRenderTargetsRenderTime = false;
  83629. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  83630. this._captureFrameTime = false;
  83631. this._frameTime = new BABYLON.PerfCounter();
  83632. this._captureRenderTime = false;
  83633. this._renderTime = new BABYLON.PerfCounter();
  83634. this._captureInterFrameTime = false;
  83635. this._interFrameTime = new BABYLON.PerfCounter();
  83636. this._captureParticlesRenderTime = false;
  83637. this._particlesRenderTime = new BABYLON.PerfCounter();
  83638. this._captureSpritesRenderTime = false;
  83639. this._spritesRenderTime = new BABYLON.PerfCounter();
  83640. this._capturePhysicsTime = false;
  83641. this._physicsTime = new BABYLON.PerfCounter();
  83642. this._captureAnimationsTime = false;
  83643. this._animationsTime = new BABYLON.PerfCounter();
  83644. // Observers
  83645. this._onBeforeActiveMeshesEvaluationObserver = null;
  83646. this._onAfterActiveMeshesEvaluationObserver = null;
  83647. this._onBeforeRenderTargetsRenderObserver = null;
  83648. this._onAfterRenderTargetsRenderObserver = null;
  83649. this._onAfterRenderObserver = null;
  83650. this._onBeforeDrawPhaseObserver = null;
  83651. this._onAfterDrawPhaseObserver = null;
  83652. this._onBeforeAnimationsObserver = null;
  83653. this._onBeforeParticlesRenderingObserver = null;
  83654. this._onAfterParticlesRenderingObserver = null;
  83655. this._onBeforeSpritesRenderingObserver = null;
  83656. this._onAfterSpritesRenderingObserver = null;
  83657. this._onBeforePhysicsObserver = null;
  83658. this._onAfterPhysicsObserver = null;
  83659. this._onAfterAnimationsObserver = null;
  83660. // Before render
  83661. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  83662. if (_this._captureActiveMeshesEvaluationTime) {
  83663. _this._activeMeshesEvaluationTime.fetchNewFrame();
  83664. }
  83665. if (_this._captureRenderTargetsRenderTime) {
  83666. _this._renderTargetsRenderTime.fetchNewFrame();
  83667. }
  83668. if (_this._captureFrameTime) {
  83669. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  83670. _this._frameTime.beginMonitoring();
  83671. }
  83672. if (_this._captureInterFrameTime) {
  83673. _this._interFrameTime.endMonitoring();
  83674. }
  83675. if (_this._captureParticlesRenderTime) {
  83676. _this._particlesRenderTime.fetchNewFrame();
  83677. }
  83678. if (_this._captureSpritesRenderTime) {
  83679. _this._spritesRenderTime.fetchNewFrame();
  83680. }
  83681. if (_this._captureAnimationsTime) {
  83682. _this._animationsTime.beginMonitoring();
  83683. }
  83684. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  83685. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  83686. });
  83687. // After render
  83688. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  83689. if (_this._captureFrameTime) {
  83690. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  83691. _this._frameTime.endMonitoring();
  83692. }
  83693. if (_this._captureRenderTime) {
  83694. _this._renderTime.endMonitoring(false);
  83695. }
  83696. if (_this._captureInterFrameTime) {
  83697. _this._interFrameTime.beginMonitoring();
  83698. }
  83699. });
  83700. }
  83701. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  83702. // Properties
  83703. /**
  83704. * Gets the perf counter used for active meshes evaluation time
  83705. */
  83706. get: function () {
  83707. return this._activeMeshesEvaluationTime;
  83708. },
  83709. enumerable: true,
  83710. configurable: true
  83711. });
  83712. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  83713. /**
  83714. * Gets the active meshes evaluation time capture status
  83715. */
  83716. get: function () {
  83717. return this._captureActiveMeshesEvaluationTime;
  83718. },
  83719. /**
  83720. * Enable or disable the active meshes evaluation time capture
  83721. */
  83722. set: function (value) {
  83723. var _this = this;
  83724. if (value === this._captureActiveMeshesEvaluationTime) {
  83725. return;
  83726. }
  83727. this._captureActiveMeshesEvaluationTime = value;
  83728. if (value) {
  83729. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  83730. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  83731. _this._activeMeshesEvaluationTime.beginMonitoring();
  83732. });
  83733. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  83734. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  83735. _this._activeMeshesEvaluationTime.endMonitoring();
  83736. });
  83737. }
  83738. else {
  83739. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83740. this._onBeforeActiveMeshesEvaluationObserver = null;
  83741. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83742. this._onAfterActiveMeshesEvaluationObserver = null;
  83743. }
  83744. },
  83745. enumerable: true,
  83746. configurable: true
  83747. });
  83748. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  83749. /**
  83750. * Gets the perf counter used for render targets render time
  83751. */
  83752. get: function () {
  83753. return this._renderTargetsRenderTime;
  83754. },
  83755. enumerable: true,
  83756. configurable: true
  83757. });
  83758. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  83759. /**
  83760. * Gets the render targets render time capture status
  83761. */
  83762. get: function () {
  83763. return this._captureRenderTargetsRenderTime;
  83764. },
  83765. /**
  83766. * Enable or disable the render targets render time capture
  83767. */
  83768. set: function (value) {
  83769. var _this = this;
  83770. if (value === this._captureRenderTargetsRenderTime) {
  83771. return;
  83772. }
  83773. this._captureRenderTargetsRenderTime = value;
  83774. if (value) {
  83775. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  83776. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  83777. _this._renderTargetsRenderTime.beginMonitoring();
  83778. });
  83779. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  83780. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  83781. _this._renderTargetsRenderTime.endMonitoring(false);
  83782. });
  83783. }
  83784. else {
  83785. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83786. this._onBeforeRenderTargetsRenderObserver = null;
  83787. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83788. this._onAfterRenderTargetsRenderObserver = null;
  83789. }
  83790. },
  83791. enumerable: true,
  83792. configurable: true
  83793. });
  83794. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  83795. /**
  83796. * Gets the perf counter used for particles render time
  83797. */
  83798. get: function () {
  83799. return this._particlesRenderTime;
  83800. },
  83801. enumerable: true,
  83802. configurable: true
  83803. });
  83804. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  83805. /**
  83806. * Gets the particles render time capture status
  83807. */
  83808. get: function () {
  83809. return this._captureParticlesRenderTime;
  83810. },
  83811. /**
  83812. * Enable or disable the particles render time capture
  83813. */
  83814. set: function (value) {
  83815. var _this = this;
  83816. if (value === this._captureParticlesRenderTime) {
  83817. return;
  83818. }
  83819. this._captureParticlesRenderTime = value;
  83820. if (value) {
  83821. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  83822. BABYLON.Tools.StartPerformanceCounter("Particles");
  83823. _this._particlesRenderTime.beginMonitoring();
  83824. });
  83825. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  83826. BABYLON.Tools.EndPerformanceCounter("Particles");
  83827. _this._particlesRenderTime.endMonitoring(false);
  83828. });
  83829. }
  83830. else {
  83831. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83832. this._onBeforeParticlesRenderingObserver = null;
  83833. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83834. this._onAfterParticlesRenderingObserver = null;
  83835. }
  83836. },
  83837. enumerable: true,
  83838. configurable: true
  83839. });
  83840. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  83841. /**
  83842. * Gets the perf counter used for sprites render time
  83843. */
  83844. get: function () {
  83845. return this._spritesRenderTime;
  83846. },
  83847. enumerable: true,
  83848. configurable: true
  83849. });
  83850. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  83851. /**
  83852. * Gets the sprites render time capture status
  83853. */
  83854. get: function () {
  83855. return this._captureSpritesRenderTime;
  83856. },
  83857. /**
  83858. * Enable or disable the sprites render time capture
  83859. */
  83860. set: function (value) {
  83861. var _this = this;
  83862. if (value === this._captureSpritesRenderTime) {
  83863. return;
  83864. }
  83865. this._captureSpritesRenderTime = value;
  83866. if (value) {
  83867. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  83868. BABYLON.Tools.StartPerformanceCounter("Sprites");
  83869. _this._spritesRenderTime.beginMonitoring();
  83870. });
  83871. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  83872. BABYLON.Tools.EndPerformanceCounter("Sprites");
  83873. _this._spritesRenderTime.endMonitoring(false);
  83874. });
  83875. }
  83876. else {
  83877. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83878. this._onBeforeSpritesRenderingObserver = null;
  83879. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83880. this._onAfterSpritesRenderingObserver = null;
  83881. }
  83882. },
  83883. enumerable: true,
  83884. configurable: true
  83885. });
  83886. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  83887. /**
  83888. * Gets the perf counter used for physics time
  83889. */
  83890. get: function () {
  83891. return this._physicsTime;
  83892. },
  83893. enumerable: true,
  83894. configurable: true
  83895. });
  83896. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  83897. /**
  83898. * Gets the physics time capture status
  83899. */
  83900. get: function () {
  83901. return this._capturePhysicsTime;
  83902. },
  83903. /**
  83904. * Enable or disable the physics time capture
  83905. */
  83906. set: function (value) {
  83907. var _this = this;
  83908. if (value === this._capturePhysicsTime) {
  83909. return;
  83910. }
  83911. this._capturePhysicsTime = value;
  83912. if (value) {
  83913. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  83914. BABYLON.Tools.StartPerformanceCounter("Physics");
  83915. _this._physicsTime.beginMonitoring();
  83916. });
  83917. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  83918. BABYLON.Tools.EndPerformanceCounter("Physics");
  83919. _this._physicsTime.endMonitoring();
  83920. });
  83921. }
  83922. else {
  83923. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83924. this._onBeforePhysicsObserver = null;
  83925. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83926. this._onAfterPhysicsObserver = null;
  83927. }
  83928. },
  83929. enumerable: true,
  83930. configurable: true
  83931. });
  83932. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  83933. /**
  83934. * Gets the perf counter used for animations time
  83935. */
  83936. get: function () {
  83937. return this._animationsTime;
  83938. },
  83939. enumerable: true,
  83940. configurable: true
  83941. });
  83942. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  83943. /**
  83944. * Gets the animations time capture status
  83945. */
  83946. get: function () {
  83947. return this._captureAnimationsTime;
  83948. },
  83949. /**
  83950. * Enable or disable the animations time capture
  83951. */
  83952. set: function (value) {
  83953. var _this = this;
  83954. if (value === this._captureAnimationsTime) {
  83955. return;
  83956. }
  83957. this._captureAnimationsTime = value;
  83958. if (value) {
  83959. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  83960. _this._animationsTime.endMonitoring();
  83961. });
  83962. }
  83963. else {
  83964. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83965. this._onAfterAnimationsObserver = null;
  83966. }
  83967. },
  83968. enumerable: true,
  83969. configurable: true
  83970. });
  83971. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  83972. /**
  83973. * Gets the perf counter used for frame time capture
  83974. */
  83975. get: function () {
  83976. return this._frameTime;
  83977. },
  83978. enumerable: true,
  83979. configurable: true
  83980. });
  83981. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  83982. /**
  83983. * Gets the frame time capture status
  83984. */
  83985. get: function () {
  83986. return this._captureFrameTime;
  83987. },
  83988. /**
  83989. * Enable or disable the frame time capture
  83990. */
  83991. set: function (value) {
  83992. this._captureFrameTime = value;
  83993. },
  83994. enumerable: true,
  83995. configurable: true
  83996. });
  83997. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  83998. /**
  83999. * Gets the perf counter used for inter-frames time capture
  84000. */
  84001. get: function () {
  84002. return this._interFrameTime;
  84003. },
  84004. enumerable: true,
  84005. configurable: true
  84006. });
  84007. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  84008. /**
  84009. * Gets the inter-frames time capture status
  84010. */
  84011. get: function () {
  84012. return this._captureInterFrameTime;
  84013. },
  84014. /**
  84015. * Enable or disable the inter-frames time capture
  84016. */
  84017. set: function (value) {
  84018. this._captureInterFrameTime = value;
  84019. },
  84020. enumerable: true,
  84021. configurable: true
  84022. });
  84023. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  84024. /**
  84025. * Gets the perf counter used for render time capture
  84026. */
  84027. get: function () {
  84028. return this._renderTime;
  84029. },
  84030. enumerable: true,
  84031. configurable: true
  84032. });
  84033. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  84034. /**
  84035. * Gets the render time capture status
  84036. */
  84037. get: function () {
  84038. return this._captureRenderTime;
  84039. },
  84040. /**
  84041. * Enable or disable the render time capture
  84042. */
  84043. set: function (value) {
  84044. var _this = this;
  84045. if (value === this._captureRenderTime) {
  84046. return;
  84047. }
  84048. this._captureRenderTime = value;
  84049. if (value) {
  84050. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  84051. _this._renderTime.beginMonitoring();
  84052. BABYLON.Tools.StartPerformanceCounter("Main render");
  84053. });
  84054. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  84055. _this._renderTime.endMonitoring(false);
  84056. BABYLON.Tools.EndPerformanceCounter("Main render");
  84057. });
  84058. }
  84059. else {
  84060. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  84061. this._onBeforeDrawPhaseObserver = null;
  84062. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  84063. this._onAfterDrawPhaseObserver = null;
  84064. }
  84065. },
  84066. enumerable: true,
  84067. configurable: true
  84068. });
  84069. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  84070. /**
  84071. * Gets the perf counter used for draw calls
  84072. */
  84073. get: function () {
  84074. return this.scene.getEngine()._drawCalls;
  84075. },
  84076. enumerable: true,
  84077. configurable: true
  84078. });
  84079. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  84080. /**
  84081. * Gets the perf counter used for texture collisions
  84082. */
  84083. get: function () {
  84084. return this.scene.getEngine()._textureCollisions;
  84085. },
  84086. enumerable: true,
  84087. configurable: true
  84088. });
  84089. SceneInstrumentation.prototype.dispose = function () {
  84090. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84091. this._onAfterRenderObserver = null;
  84092. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  84093. this._onBeforeActiveMeshesEvaluationObserver = null;
  84094. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  84095. this._onAfterActiveMeshesEvaluationObserver = null;
  84096. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  84097. this._onBeforeRenderTargetsRenderObserver = null;
  84098. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  84099. this._onAfterRenderTargetsRenderObserver = null;
  84100. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  84101. this._onBeforeAnimationsObserver = null;
  84102. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  84103. this._onBeforeParticlesRenderingObserver = null;
  84104. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  84105. this._onAfterParticlesRenderingObserver = null;
  84106. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  84107. this._onBeforeSpritesRenderingObserver = null;
  84108. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  84109. this._onAfterSpritesRenderingObserver = null;
  84110. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  84111. this._onBeforeDrawPhaseObserver = null;
  84112. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  84113. this._onAfterDrawPhaseObserver = null;
  84114. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  84115. this._onBeforePhysicsObserver = null;
  84116. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  84117. this._onAfterPhysicsObserver = null;
  84118. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  84119. this._onAfterAnimationsObserver = null;
  84120. this.scene = null;
  84121. };
  84122. return SceneInstrumentation;
  84123. }());
  84124. BABYLON.SceneInstrumentation = SceneInstrumentation;
  84125. })(BABYLON || (BABYLON = {}));
  84126. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  84127. var BABYLON;
  84128. (function (BABYLON) {
  84129. var _TimeToken = /** @class */ (function () {
  84130. function _TimeToken() {
  84131. this._timeElapsedQueryEnded = false;
  84132. }
  84133. return _TimeToken;
  84134. }());
  84135. BABYLON._TimeToken = _TimeToken;
  84136. })(BABYLON || (BABYLON = {}));
  84137. //# sourceMappingURL=babylon.timeToken.js.map
  84138. var BABYLON;
  84139. (function (BABYLON) {
  84140. /**
  84141. * Background material defines definition.
  84142. * @ignore Mainly internal Use
  84143. */
  84144. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  84145. __extends(BackgroundMaterialDefines, _super);
  84146. /**
  84147. * Constructor of the defines.
  84148. */
  84149. function BackgroundMaterialDefines() {
  84150. var _this = _super.call(this) || this;
  84151. /**
  84152. * True if the diffuse texture is in use.
  84153. */
  84154. _this.DIFFUSE = false;
  84155. /**
  84156. * The direct UV channel to use.
  84157. */
  84158. _this.DIFFUSEDIRECTUV = 0;
  84159. /**
  84160. * True if the diffuse texture is in gamma space.
  84161. */
  84162. _this.GAMMADIFFUSE = false;
  84163. /**
  84164. * True if the diffuse texture has opacity in the alpha channel.
  84165. */
  84166. _this.DIFFUSEHASALPHA = false;
  84167. /**
  84168. * True if you want the material to fade to transparent at grazing angle.
  84169. */
  84170. _this.OPACITYFRESNEL = false;
  84171. /**
  84172. * True if an extra blur needs to be added in the reflection.
  84173. */
  84174. _this.REFLECTIONBLUR = false;
  84175. /**
  84176. * True if you want the material to fade to reflection at grazing angle.
  84177. */
  84178. _this.REFLECTIONFRESNEL = false;
  84179. /**
  84180. * True if you want the material to falloff as far as you move away from the scene center.
  84181. */
  84182. _this.REFLECTIONFALLOFF = false;
  84183. /**
  84184. * False if the current Webgl implementation does not support the texture lod extension.
  84185. */
  84186. _this.TEXTURELODSUPPORT = false;
  84187. /**
  84188. * True to ensure the data are premultiplied.
  84189. */
  84190. _this.PREMULTIPLYALPHA = false;
  84191. /**
  84192. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  84193. */
  84194. _this.USERGBCOLOR = false;
  84195. /**
  84196. * True to add noise in order to reduce the banding effect.
  84197. */
  84198. _this.NOISE = false;
  84199. // Image Processing Configuration.
  84200. _this.IMAGEPROCESSING = false;
  84201. _this.VIGNETTE = false;
  84202. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84203. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84204. _this.TONEMAPPING = false;
  84205. _this.CONTRAST = false;
  84206. _this.COLORCURVES = false;
  84207. _this.COLORGRADING = false;
  84208. _this.COLORGRADING3D = false;
  84209. _this.SAMPLER3DGREENDEPTH = false;
  84210. _this.SAMPLER3DBGRMAP = false;
  84211. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84212. _this.EXPOSURE = false;
  84213. // Reflection.
  84214. _this.REFLECTION = false;
  84215. _this.REFLECTIONMAP_3D = false;
  84216. _this.REFLECTIONMAP_SPHERICAL = false;
  84217. _this.REFLECTIONMAP_PLANAR = false;
  84218. _this.REFLECTIONMAP_CUBIC = false;
  84219. _this.REFLECTIONMAP_PROJECTION = false;
  84220. _this.REFLECTIONMAP_SKYBOX = false;
  84221. _this.REFLECTIONMAP_EXPLICIT = false;
  84222. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84223. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84224. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84225. _this.INVERTCUBICMAP = false;
  84226. _this.REFLECTIONMAP_OPPOSITEZ = false;
  84227. _this.LODINREFLECTIONALPHA = false;
  84228. _this.GAMMAREFLECTION = false;
  84229. // Default BJS.
  84230. _this.MAINUV1 = false;
  84231. _this.MAINUV2 = false;
  84232. _this.UV1 = false;
  84233. _this.UV2 = false;
  84234. _this.CLIPPLANE = false;
  84235. _this.POINTSIZE = false;
  84236. _this.FOG = false;
  84237. _this.NORMAL = false;
  84238. _this.NUM_BONE_INFLUENCERS = 0;
  84239. _this.BonesPerMesh = 0;
  84240. _this.INSTANCES = false;
  84241. _this.SHADOWFLOAT = false;
  84242. _this.rebuild();
  84243. return _this;
  84244. }
  84245. return BackgroundMaterialDefines;
  84246. }(BABYLON.MaterialDefines));
  84247. /**
  84248. * Background material used to create an efficient environement around your scene.
  84249. */
  84250. var BackgroundMaterial = /** @class */ (function (_super) {
  84251. __extends(BackgroundMaterial, _super);
  84252. /**
  84253. * Instantiates a Background Material in the given scene
  84254. * @param name The friendly name of the material
  84255. * @param scene The scene to add the material to
  84256. */
  84257. function BackgroundMaterial(name, scene) {
  84258. var _this = _super.call(this, name, scene) || this;
  84259. /**
  84260. * Key light Color (multiply against the R channel of the environement texture)
  84261. */
  84262. _this.primaryColor = BABYLON.Color3.White();
  84263. /**
  84264. * Key light Level (allowing HDR output of the background)
  84265. */
  84266. _this.primaryLevel = 1;
  84267. /**
  84268. * Secondary light Color (multiply against the G channel of the environement texture)
  84269. */
  84270. _this.secondaryColor = BABYLON.Color3.Gray();
  84271. /**
  84272. * Secondary light Level (allowing HDR output of the background)
  84273. */
  84274. _this.secondaryLevel = 1;
  84275. /**
  84276. * Tertiary light Color (multiply against the B channel of the environement texture)
  84277. */
  84278. _this.tertiaryColor = BABYLON.Color3.Black();
  84279. /**
  84280. * Tertiary light Level (allowing HDR output of the background)
  84281. */
  84282. _this.tertiaryLevel = 1;
  84283. /**
  84284. * Reflection Texture used in the material.
  84285. * Should be author in a specific way for the best result (refer to the documentation).
  84286. */
  84287. _this.reflectionTexture = null;
  84288. /**
  84289. * Reflection Texture level of blur.
  84290. *
  84291. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  84292. * texture twice.
  84293. */
  84294. _this.reflectionBlur = 0;
  84295. /**
  84296. * Diffuse Texture used in the material.
  84297. * Should be author in a specific way for the best result (refer to the documentation).
  84298. */
  84299. _this.diffuseTexture = null;
  84300. _this._shadowLights = null;
  84301. /**
  84302. * Specify the list of lights casting shadow on the material.
  84303. * All scene shadow lights will be included if null.
  84304. */
  84305. _this.shadowLights = null;
  84306. /**
  84307. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  84308. * soft lighting on the background.
  84309. */
  84310. _this.shadowBlurScale = 1;
  84311. /**
  84312. * Helps adjusting the shadow to a softer level if required.
  84313. * 0 means black shadows and 1 means no shadows.
  84314. */
  84315. _this.shadowLevel = 0;
  84316. /**
  84317. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  84318. * It is usually zero but might be interesting to modify according to your setup.
  84319. */
  84320. _this.sceneCenter = BABYLON.Vector3.Zero();
  84321. /**
  84322. * This helps specifying that the material is falling off to the sky box at grazing angle.
  84323. * This helps ensuring a nice transition when the camera goes under the ground.
  84324. */
  84325. _this.opacityFresnel = true;
  84326. /**
  84327. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  84328. * This helps adding a mirror texture on the ground.
  84329. */
  84330. _this.reflectionFresnel = false;
  84331. /**
  84332. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  84333. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  84334. */
  84335. _this.reflectionFalloffDistance = 0.0;
  84336. /**
  84337. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  84338. */
  84339. _this.reflectionAmount = 1.0;
  84340. /**
  84341. * This specifies the weight of the reflection at grazing angle.
  84342. */
  84343. _this.reflectionReflectance0 = 0.05;
  84344. /**
  84345. * This specifies the weight of the reflection at a perpendicular point of view.
  84346. */
  84347. _this.reflectionReflectance90 = 0.5;
  84348. /**
  84349. * Helps to directly use the maps channels instead of their level.
  84350. */
  84351. _this.useRGBColor = true;
  84352. /**
  84353. * This helps reducing the banding effect that could occur on the background.
  84354. */
  84355. _this.enableNoise = false;
  84356. _this._maxSimultaneousLights = 4;
  84357. /**
  84358. * Number of Simultaneous lights allowed on the material.
  84359. */
  84360. _this.maxSimultaneousLights = 4;
  84361. /**
  84362. * Keep track of the image processing observer to allow dispose and replace.
  84363. */
  84364. _this._imageProcessingObserver = null;
  84365. // Temp values kept as cache in the material.
  84366. _this._renderTargets = new BABYLON.SmartArray(16);
  84367. _this._reflectionControls = BABYLON.Vector4.Zero();
  84368. // Setup the default processing configuration to the scene.
  84369. _this._attachImageProcessingConfiguration(null);
  84370. _this.getRenderTargetTextures = function () {
  84371. _this._renderTargets.reset();
  84372. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  84373. _this._renderTargets.push(_this._diffuseTexture);
  84374. }
  84375. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  84376. _this._renderTargets.push(_this._reflectionTexture);
  84377. }
  84378. return _this._renderTargets;
  84379. };
  84380. return _this;
  84381. }
  84382. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  84383. /**
  84384. * Sets the reflection reflectance fresnel values according to the default standard
  84385. * empirically know to work well :-)
  84386. */
  84387. set: function (value) {
  84388. var reflectionWeight = value;
  84389. if (reflectionWeight < 0.5) {
  84390. reflectionWeight = reflectionWeight * 2.0;
  84391. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  84392. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  84393. }
  84394. else {
  84395. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  84396. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  84397. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  84398. }
  84399. },
  84400. enumerable: true,
  84401. configurable: true
  84402. });
  84403. /**
  84404. * Attaches a new image processing configuration to the PBR Material.
  84405. * @param configuration (if null the scene configuration will be use)
  84406. */
  84407. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  84408. var _this = this;
  84409. if (configuration === this._imageProcessingConfiguration) {
  84410. return;
  84411. }
  84412. // Detaches observer.
  84413. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84414. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84415. }
  84416. // Pick the scene configuration if needed.
  84417. if (!configuration) {
  84418. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  84419. }
  84420. else {
  84421. this._imageProcessingConfiguration = configuration;
  84422. }
  84423. // Attaches observer.
  84424. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84425. _this._markAllSubMeshesAsImageProcessingDirty();
  84426. });
  84427. };
  84428. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  84429. /**
  84430. * Gets the image processing configuration used either in this material.
  84431. */
  84432. get: function () {
  84433. return this._imageProcessingConfiguration;
  84434. },
  84435. /**
  84436. * Sets the Default image processing configuration used either in the this material.
  84437. *
  84438. * If sets to null, the scene one is in use.
  84439. */
  84440. set: function (value) {
  84441. this._attachImageProcessingConfiguration(value);
  84442. // Ensure the effect will be rebuilt.
  84443. this._markAllSubMeshesAsTexturesDirty();
  84444. },
  84445. enumerable: true,
  84446. configurable: true
  84447. });
  84448. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  84449. /**
  84450. * Gets wether the color curves effect is enabled.
  84451. */
  84452. get: function () {
  84453. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84454. },
  84455. /**
  84456. * Sets wether the color curves effect is enabled.
  84457. */
  84458. set: function (value) {
  84459. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84460. },
  84461. enumerable: true,
  84462. configurable: true
  84463. });
  84464. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  84465. /**
  84466. * Gets wether the color grading effect is enabled.
  84467. */
  84468. get: function () {
  84469. return this.imageProcessingConfiguration.colorGradingEnabled;
  84470. },
  84471. /**
  84472. * Gets wether the color grading effect is enabled.
  84473. */
  84474. set: function (value) {
  84475. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84476. },
  84477. enumerable: true,
  84478. configurable: true
  84479. });
  84480. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  84481. /**
  84482. * Gets wether tonemapping is enabled or not.
  84483. */
  84484. get: function () {
  84485. return this._imageProcessingConfiguration.toneMappingEnabled;
  84486. },
  84487. /**
  84488. * Sets wether tonemapping is enabled or not
  84489. */
  84490. set: function (value) {
  84491. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84492. },
  84493. enumerable: true,
  84494. configurable: true
  84495. });
  84496. ;
  84497. ;
  84498. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  84499. /**
  84500. * The camera exposure used on this material.
  84501. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84502. * This corresponds to a photographic exposure.
  84503. */
  84504. get: function () {
  84505. return this._imageProcessingConfiguration.exposure;
  84506. },
  84507. /**
  84508. * The camera exposure used on this material.
  84509. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84510. * This corresponds to a photographic exposure.
  84511. */
  84512. set: function (value) {
  84513. this._imageProcessingConfiguration.exposure = value;
  84514. },
  84515. enumerable: true,
  84516. configurable: true
  84517. });
  84518. ;
  84519. ;
  84520. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  84521. /**
  84522. * Gets The camera contrast used on this material.
  84523. */
  84524. get: function () {
  84525. return this._imageProcessingConfiguration.contrast;
  84526. },
  84527. /**
  84528. * Sets The camera contrast used on this material.
  84529. */
  84530. set: function (value) {
  84531. this._imageProcessingConfiguration.contrast = value;
  84532. },
  84533. enumerable: true,
  84534. configurable: true
  84535. });
  84536. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  84537. /**
  84538. * Gets the Color Grading 2D Lookup Texture.
  84539. */
  84540. get: function () {
  84541. return this._imageProcessingConfiguration.colorGradingTexture;
  84542. },
  84543. /**
  84544. * Sets the Color Grading 2D Lookup Texture.
  84545. */
  84546. set: function (value) {
  84547. this.imageProcessingConfiguration.colorGradingTexture = value;
  84548. },
  84549. enumerable: true,
  84550. configurable: true
  84551. });
  84552. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  84553. /**
  84554. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84555. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84556. * 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;
  84557. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84558. */
  84559. get: function () {
  84560. return this.imageProcessingConfiguration.colorCurves;
  84561. },
  84562. /**
  84563. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84564. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84565. * 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;
  84566. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84567. */
  84568. set: function (value) {
  84569. this.imageProcessingConfiguration.colorCurves = value;
  84570. },
  84571. enumerable: true,
  84572. configurable: true
  84573. });
  84574. /**
  84575. * The entire material has been created in order to prevent overdraw.
  84576. * @returns false
  84577. */
  84578. BackgroundMaterial.prototype.needAlphaTesting = function () {
  84579. return true;
  84580. };
  84581. /**
  84582. * The entire material has been created in order to prevent overdraw.
  84583. * @returns true if blending is enable
  84584. */
  84585. BackgroundMaterial.prototype.needAlphaBlending = function () {
  84586. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  84587. };
  84588. /**
  84589. * Checks wether the material is ready to be rendered for a given mesh.
  84590. * @param mesh The mesh to render
  84591. * @param subMesh The submesh to check against
  84592. * @param useInstances Specify wether or not the material is used with instances
  84593. * @returns true if all the dependencies are ready (Textures, Effects...)
  84594. */
  84595. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  84596. var _this = this;
  84597. if (useInstances === void 0) { useInstances = false; }
  84598. if (subMesh.effect && this.isFrozen) {
  84599. if (this._wasPreviouslyReady) {
  84600. return true;
  84601. }
  84602. }
  84603. if (!subMesh._materialDefines) {
  84604. subMesh._materialDefines = new BackgroundMaterialDefines();
  84605. }
  84606. var scene = this.getScene();
  84607. var defines = subMesh._materialDefines;
  84608. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  84609. if (defines._renderId === scene.getRenderId()) {
  84610. return true;
  84611. }
  84612. }
  84613. var engine = scene.getEngine();
  84614. // Lights
  84615. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  84616. defines._needNormals = true;
  84617. // Textures
  84618. if (defines._areTexturesDirty) {
  84619. defines._needUVs = false;
  84620. if (scene.texturesEnabled) {
  84621. if (scene.getEngine().getCaps().textureLOD) {
  84622. defines.TEXTURELODSUPPORT = true;
  84623. }
  84624. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84625. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  84626. return false;
  84627. }
  84628. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  84629. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  84630. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  84631. defines.OPACITYFRESNEL = this._opacityFresnel;
  84632. }
  84633. else {
  84634. defines.DIFFUSE = false;
  84635. defines.DIFFUSEHASALPHA = false;
  84636. defines.GAMMADIFFUSE = false;
  84637. defines.OPACITYFRESNEL = false;
  84638. }
  84639. var reflectionTexture = this._reflectionTexture;
  84640. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84641. if (!reflectionTexture.isReadyOrNotBlocking()) {
  84642. return false;
  84643. }
  84644. defines.REFLECTION = true;
  84645. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  84646. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  84647. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  84648. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  84649. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  84650. defines.INVERTCUBICMAP = true;
  84651. }
  84652. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  84653. switch (reflectionTexture.coordinatesMode) {
  84654. case BABYLON.Texture.CUBIC_MODE:
  84655. case BABYLON.Texture.INVCUBIC_MODE:
  84656. defines.REFLECTIONMAP_CUBIC = true;
  84657. break;
  84658. case BABYLON.Texture.EXPLICIT_MODE:
  84659. defines.REFLECTIONMAP_EXPLICIT = true;
  84660. break;
  84661. case BABYLON.Texture.PLANAR_MODE:
  84662. defines.REFLECTIONMAP_PLANAR = true;
  84663. break;
  84664. case BABYLON.Texture.PROJECTION_MODE:
  84665. defines.REFLECTIONMAP_PROJECTION = true;
  84666. break;
  84667. case BABYLON.Texture.SKYBOX_MODE:
  84668. defines.REFLECTIONMAP_SKYBOX = true;
  84669. break;
  84670. case BABYLON.Texture.SPHERICAL_MODE:
  84671. defines.REFLECTIONMAP_SPHERICAL = true;
  84672. break;
  84673. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  84674. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  84675. break;
  84676. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  84677. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  84678. break;
  84679. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  84680. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  84681. break;
  84682. }
  84683. if (this.reflectionFresnel) {
  84684. defines.REFLECTIONFRESNEL = true;
  84685. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  84686. this._reflectionControls.x = this.reflectionAmount;
  84687. this._reflectionControls.y = this.reflectionReflectance0;
  84688. this._reflectionControls.z = this.reflectionReflectance90;
  84689. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  84690. }
  84691. else {
  84692. defines.REFLECTIONFRESNEL = false;
  84693. defines.REFLECTIONFALLOFF = false;
  84694. }
  84695. }
  84696. else {
  84697. defines.REFLECTION = false;
  84698. defines.REFLECTIONFALLOFF = false;
  84699. defines.REFLECTIONBLUR = false;
  84700. defines.REFLECTIONMAP_3D = false;
  84701. defines.REFLECTIONMAP_SPHERICAL = false;
  84702. defines.REFLECTIONMAP_PLANAR = false;
  84703. defines.REFLECTIONMAP_CUBIC = false;
  84704. defines.REFLECTIONMAP_PROJECTION = false;
  84705. defines.REFLECTIONMAP_SKYBOX = false;
  84706. defines.REFLECTIONMAP_EXPLICIT = false;
  84707. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84708. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84709. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84710. defines.INVERTCUBICMAP = false;
  84711. defines.REFLECTIONMAP_OPPOSITEZ = false;
  84712. defines.LODINREFLECTIONALPHA = false;
  84713. defines.GAMMAREFLECTION = false;
  84714. }
  84715. }
  84716. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  84717. defines.USERGBCOLOR = this._useRGBColor;
  84718. defines.NOISE = this._enableNoise;
  84719. }
  84720. if (defines._areImageProcessingDirty) {
  84721. if (!this._imageProcessingConfiguration.isReady()) {
  84722. return false;
  84723. }
  84724. this._imageProcessingConfiguration.prepareDefines(defines);
  84725. }
  84726. // Misc.
  84727. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  84728. // Values that need to be evaluated on every frame
  84729. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  84730. // Attribs
  84731. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  84732. if (mesh) {
  84733. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84734. mesh.createNormals(true);
  84735. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  84736. }
  84737. }
  84738. }
  84739. // Get correct effect
  84740. if (defines.isDirty) {
  84741. defines.markAsProcessed();
  84742. scene.resetCachedMaterial();
  84743. // Fallbacks
  84744. var fallbacks = new BABYLON.EffectFallbacks();
  84745. if (defines.FOG) {
  84746. fallbacks.addFallback(0, "FOG");
  84747. }
  84748. if (defines.POINTSIZE) {
  84749. fallbacks.addFallback(1, "POINTSIZE");
  84750. }
  84751. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  84752. if (defines.NUM_BONE_INFLUENCERS > 0) {
  84753. fallbacks.addCPUSkinningFallback(0, mesh);
  84754. }
  84755. //Attributes
  84756. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84757. if (defines.NORMAL) {
  84758. attribs.push(BABYLON.VertexBuffer.NormalKind);
  84759. }
  84760. if (defines.UV1) {
  84761. attribs.push(BABYLON.VertexBuffer.UVKind);
  84762. }
  84763. if (defines.UV2) {
  84764. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84765. }
  84766. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  84767. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  84768. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  84769. "vFogInfos", "vFogColor", "pointSize",
  84770. "vClipPlane", "mBones",
  84771. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  84772. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  84773. "shadowLevel", "alpha",
  84774. "vBackgroundCenter", "vReflectionControl",
  84775. "vDiffuseInfos", "diffuseMatrix",
  84776. ];
  84777. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  84778. var uniformBuffers = ["Material", "Scene"];
  84779. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  84780. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  84781. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  84782. uniformsNames: uniforms,
  84783. uniformBuffersNames: uniformBuffers,
  84784. samplers: samplers,
  84785. defines: defines,
  84786. maxSimultaneousLights: this._maxSimultaneousLights
  84787. });
  84788. var onCompiled = function (effect) {
  84789. if (_this.onCompiled) {
  84790. _this.onCompiled(effect);
  84791. }
  84792. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  84793. };
  84794. var join = defines.toString();
  84795. subMesh.setEffect(scene.getEngine().createEffect("background", {
  84796. attributes: attribs,
  84797. uniformsNames: uniforms,
  84798. uniformBuffersNames: uniformBuffers,
  84799. samplers: samplers,
  84800. defines: join,
  84801. fallbacks: fallbacks,
  84802. onCompiled: onCompiled,
  84803. onError: this.onError,
  84804. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  84805. }, engine), defines);
  84806. this.buildUniformLayout();
  84807. }
  84808. if (!subMesh.effect || !subMesh.effect.isReady()) {
  84809. return false;
  84810. }
  84811. defines._renderId = scene.getRenderId();
  84812. this._wasPreviouslyReady = true;
  84813. return true;
  84814. };
  84815. /**
  84816. * Build the uniform buffer used in the material.
  84817. */
  84818. BackgroundMaterial.prototype.buildUniformLayout = function () {
  84819. // Order is important !
  84820. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  84821. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  84822. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  84823. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  84824. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  84825. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  84826. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  84827. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  84828. this._uniformBuffer.addUniform("pointSize", 1);
  84829. this._uniformBuffer.addUniform("shadowLevel", 1);
  84830. this._uniformBuffer.addUniform("alpha", 1);
  84831. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  84832. this._uniformBuffer.addUniform("vReflectionControl", 4);
  84833. this._uniformBuffer.create();
  84834. };
  84835. /**
  84836. * Unbind the material.
  84837. */
  84838. BackgroundMaterial.prototype.unbind = function () {
  84839. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  84840. this._uniformBuffer.setTexture("diffuseSampler", null);
  84841. }
  84842. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  84843. this._uniformBuffer.setTexture("reflectionSampler", null);
  84844. }
  84845. _super.prototype.unbind.call(this);
  84846. };
  84847. /**
  84848. * Bind only the world matrix to the material.
  84849. * @param world The world matrix to bind.
  84850. */
  84851. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  84852. this._activeEffect.setMatrix("world", world);
  84853. };
  84854. /**
  84855. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  84856. * @param world The world matrix to bind.
  84857. * @param subMesh The submesh to bind for.
  84858. */
  84859. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  84860. var scene = this.getScene();
  84861. var defines = subMesh._materialDefines;
  84862. if (!defines) {
  84863. return;
  84864. }
  84865. var effect = subMesh.effect;
  84866. if (!effect) {
  84867. return;
  84868. }
  84869. this._activeEffect = effect;
  84870. // Matrices
  84871. this.bindOnlyWorldMatrix(world);
  84872. // Bones
  84873. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  84874. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  84875. if (mustRebind) {
  84876. this._uniformBuffer.bindToEffect(effect, "Material");
  84877. this.bindViewProjection(effect);
  84878. var reflectionTexture = this._reflectionTexture;
  84879. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  84880. // Texture uniforms
  84881. if (scene.texturesEnabled) {
  84882. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84883. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  84884. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  84885. }
  84886. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84887. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  84888. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  84889. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  84890. }
  84891. }
  84892. if (this.shadowLevel > 0) {
  84893. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  84894. }
  84895. this._uniformBuffer.updateFloat("alpha", this.alpha);
  84896. // Point size
  84897. if (this.pointsCloud) {
  84898. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  84899. }
  84900. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  84901. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  84902. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  84903. }
  84904. // Textures
  84905. if (scene.texturesEnabled) {
  84906. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84907. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  84908. }
  84909. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84910. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  84911. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84912. }
  84913. else if (!defines.REFLECTIONBLUR) {
  84914. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84915. }
  84916. else {
  84917. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  84918. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  84919. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  84920. }
  84921. if (defines.REFLECTIONFRESNEL) {
  84922. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  84923. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  84924. }
  84925. }
  84926. }
  84927. // Clip plane
  84928. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  84929. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  84930. }
  84931. if (mustRebind || !this.isFrozen) {
  84932. if (scene.lightsEnabled) {
  84933. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  84934. }
  84935. // View
  84936. this.bindView(effect);
  84937. // Fog
  84938. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84939. // image processing
  84940. this._imageProcessingConfiguration.bind(this._activeEffect);
  84941. }
  84942. this._uniformBuffer.update();
  84943. this._afterBind(mesh);
  84944. };
  84945. /**
  84946. * Dispose the material.
  84947. * @param forceDisposeEffect Force disposal of the associated effect.
  84948. * @param forceDisposeTextures Force disposal of the associated textures.
  84949. */
  84950. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  84951. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  84952. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  84953. if (forceDisposeTextures) {
  84954. if (this.diffuseTexture) {
  84955. this.diffuseTexture.dispose();
  84956. }
  84957. if (this.reflectionTexture) {
  84958. this.reflectionTexture.dispose();
  84959. }
  84960. }
  84961. this._renderTargets.dispose();
  84962. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84963. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84964. }
  84965. _super.prototype.dispose.call(this, forceDisposeEffect);
  84966. };
  84967. /**
  84968. * Clones the material.
  84969. * @param name The cloned name.
  84970. * @returns The cloned material.
  84971. */
  84972. BackgroundMaterial.prototype.clone = function (name) {
  84973. var _this = this;
  84974. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  84975. };
  84976. /**
  84977. * Serializes the current material to its JSON representation.
  84978. * @returns The JSON representation.
  84979. */
  84980. BackgroundMaterial.prototype.serialize = function () {
  84981. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84982. serializationObject.customType = "BABYLON.BackgroundMaterial";
  84983. return serializationObject;
  84984. };
  84985. /**
  84986. * Gets the class name of the material
  84987. * @returns "BackgroundMaterial"
  84988. */
  84989. BackgroundMaterial.prototype.getClassName = function () {
  84990. return "BackgroundMaterial";
  84991. };
  84992. /**
  84993. * Parse a JSON input to create back a background material.
  84994. * @param source The JSON data to parse
  84995. * @param scene The scene to create the parsed material in
  84996. * @param rootUrl The root url of the assets the material depends upon
  84997. * @returns the instantiated BackgroundMaterial.
  84998. */
  84999. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  85000. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  85001. };
  85002. /**
  85003. * Standard reflectance value at parallel view angle.
  85004. */
  85005. BackgroundMaterial.StandardReflectance0 = 0.05;
  85006. /**
  85007. * Standard reflectance value at grazing angle.
  85008. */
  85009. BackgroundMaterial.StandardReflectance90 = 0.5;
  85010. __decorate([
  85011. BABYLON.serializeAsColor3()
  85012. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  85013. __decorate([
  85014. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85015. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  85016. __decorate([
  85017. BABYLON.serialize()
  85018. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  85019. __decorate([
  85020. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85021. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  85022. __decorate([
  85023. BABYLON.serializeAsColor3()
  85024. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  85025. __decorate([
  85026. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85027. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  85028. __decorate([
  85029. BABYLON.serialize()
  85030. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  85031. __decorate([
  85032. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85033. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  85034. __decorate([
  85035. BABYLON.serializeAsColor3()
  85036. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  85037. __decorate([
  85038. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85039. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  85040. __decorate([
  85041. BABYLON.serialize()
  85042. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  85043. __decorate([
  85044. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85045. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  85046. __decorate([
  85047. BABYLON.serializeAsTexture()
  85048. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  85049. __decorate([
  85050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85051. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  85052. __decorate([
  85053. BABYLON.serialize()
  85054. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  85055. __decorate([
  85056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85057. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  85058. __decorate([
  85059. BABYLON.serializeAsTexture()
  85060. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  85061. __decorate([
  85062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85063. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  85064. __decorate([
  85065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85066. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  85067. __decorate([
  85068. BABYLON.serialize()
  85069. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  85070. __decorate([
  85071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85072. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  85073. __decorate([
  85074. BABYLON.serialize()
  85075. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  85076. __decorate([
  85077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85078. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  85079. __decorate([
  85080. BABYLON.serializeAsVector3()
  85081. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  85082. __decorate([
  85083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85084. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  85085. __decorate([
  85086. BABYLON.serialize()
  85087. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  85088. __decorate([
  85089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85090. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  85091. __decorate([
  85092. BABYLON.serialize()
  85093. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  85094. __decorate([
  85095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85096. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  85097. __decorate([
  85098. BABYLON.serialize()
  85099. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  85100. __decorate([
  85101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85102. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  85103. __decorate([
  85104. BABYLON.serialize()
  85105. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  85106. __decorate([
  85107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85108. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  85109. __decorate([
  85110. BABYLON.serialize()
  85111. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  85112. __decorate([
  85113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85114. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  85115. __decorate([
  85116. BABYLON.serialize()
  85117. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  85118. __decorate([
  85119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85120. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  85121. __decorate([
  85122. BABYLON.serialize()
  85123. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  85124. __decorate([
  85125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85126. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  85127. __decorate([
  85128. BABYLON.serialize()
  85129. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  85130. __decorate([
  85131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85132. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  85133. __decorate([
  85134. BABYLON.serialize()
  85135. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  85136. __decorate([
  85137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85138. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  85139. __decorate([
  85140. BABYLON.serializeAsImageProcessingConfiguration()
  85141. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  85142. return BackgroundMaterial;
  85143. }(BABYLON.PushMaterial));
  85144. BABYLON.BackgroundMaterial = BackgroundMaterial;
  85145. })(BABYLON || (BABYLON = {}));
  85146. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  85147. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85148. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85149. s = arguments[i];
  85150. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85151. t[p] = s[p];
  85152. }
  85153. return t;
  85154. };
  85155. var BABYLON;
  85156. (function (BABYLON) {
  85157. /**
  85158. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  85159. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  85160. * It also helps with the default setup of your imageProcessing configuration.
  85161. */
  85162. var EnvironmentHelper = /** @class */ (function () {
  85163. /**
  85164. * constructor
  85165. * @param options
  85166. * @param scene The scene to add the material to
  85167. */
  85168. function EnvironmentHelper(options, scene) {
  85169. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  85170. this._scene = scene;
  85171. this._setupBackground();
  85172. this._setupImageProcessing();
  85173. }
  85174. /**
  85175. * Creates the default options for the helper.
  85176. */
  85177. EnvironmentHelper._getDefaultOptions = function () {
  85178. return {
  85179. createGround: true,
  85180. groundSize: 15,
  85181. groundTexture: this._groundTextureCDNUrl,
  85182. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85183. groundOpacity: 0.9,
  85184. enableGroundShadow: true,
  85185. groundShadowLevel: 0.5,
  85186. enableGroundMirror: false,
  85187. groundMirrorSizeRatio: 0.3,
  85188. groundMirrorBlurKernel: 64,
  85189. groundMirrorAmount: 1,
  85190. groundMirrorFresnelWeight: 1,
  85191. groundMirrorFallOffDistance: 0,
  85192. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  85193. groundYBias: 0.00001,
  85194. createSkybox: true,
  85195. skyboxSize: 20,
  85196. skyboxTexture: this._skyboxTextureCDNUrl,
  85197. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85198. backgroundYRotation: 0,
  85199. sizeAuto: true,
  85200. rootPosition: BABYLON.Vector3.Zero(),
  85201. setupImageProcessing: true,
  85202. environmentTexture: this._environmentTextureCDNUrl,
  85203. cameraExposure: 0.8,
  85204. cameraContrast: 1.2,
  85205. toneMappingEnabled: true,
  85206. };
  85207. };
  85208. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  85209. /**
  85210. * Gets the root mesh created by the helper.
  85211. */
  85212. get: function () {
  85213. return this._rootMesh;
  85214. },
  85215. enumerable: true,
  85216. configurable: true
  85217. });
  85218. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  85219. /**
  85220. * Gets the skybox created by the helper.
  85221. */
  85222. get: function () {
  85223. return this._skybox;
  85224. },
  85225. enumerable: true,
  85226. configurable: true
  85227. });
  85228. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  85229. /**
  85230. * Gets the skybox texture created by the helper.
  85231. */
  85232. get: function () {
  85233. return this._skyboxTexture;
  85234. },
  85235. enumerable: true,
  85236. configurable: true
  85237. });
  85238. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  85239. /**
  85240. * Gets the skybox material created by the helper.
  85241. */
  85242. get: function () {
  85243. return this._skyboxMaterial;
  85244. },
  85245. enumerable: true,
  85246. configurable: true
  85247. });
  85248. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  85249. /**
  85250. * Gets the ground mesh created by the helper.
  85251. */
  85252. get: function () {
  85253. return this._ground;
  85254. },
  85255. enumerable: true,
  85256. configurable: true
  85257. });
  85258. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  85259. /**
  85260. * Gets the ground texture created by the helper.
  85261. */
  85262. get: function () {
  85263. return this._groundTexture;
  85264. },
  85265. enumerable: true,
  85266. configurable: true
  85267. });
  85268. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  85269. /**
  85270. * Gets the ground mirror created by the helper.
  85271. */
  85272. get: function () {
  85273. return this._groundMirror;
  85274. },
  85275. enumerable: true,
  85276. configurable: true
  85277. });
  85278. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  85279. /**
  85280. * Gets the ground mirror render list to helps pushing the meshes
  85281. * you wish in the ground reflection.
  85282. */
  85283. get: function () {
  85284. if (this._groundMirror) {
  85285. return this._groundMirror.renderList;
  85286. }
  85287. return null;
  85288. },
  85289. enumerable: true,
  85290. configurable: true
  85291. });
  85292. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  85293. /**
  85294. * Gets the ground material created by the helper.
  85295. */
  85296. get: function () {
  85297. return this._groundMaterial;
  85298. },
  85299. enumerable: true,
  85300. configurable: true
  85301. });
  85302. /**
  85303. * Updates the background according to the new options
  85304. * @param options
  85305. */
  85306. EnvironmentHelper.prototype.updateOptions = function (options) {
  85307. var newOptions = __assign({}, this._options, options);
  85308. if (this._ground && !newOptions.createGround) {
  85309. this._ground.dispose();
  85310. this._ground = null;
  85311. }
  85312. if (this._groundMaterial && !newOptions.createGround) {
  85313. this._groundMaterial.dispose();
  85314. this._groundMaterial = null;
  85315. }
  85316. if (this._groundTexture) {
  85317. if (this._options.groundTexture != newOptions.groundTexture) {
  85318. this._groundTexture.dispose();
  85319. this._groundTexture = null;
  85320. }
  85321. }
  85322. if (this._skybox && !newOptions.createSkybox) {
  85323. this._skybox.dispose();
  85324. this._skybox = null;
  85325. }
  85326. if (this._skyboxMaterial && !newOptions.createSkybox) {
  85327. this._skyboxMaterial.dispose();
  85328. this._skyboxMaterial = null;
  85329. }
  85330. if (this._skyboxTexture) {
  85331. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  85332. this._skyboxTexture.dispose();
  85333. this._skyboxTexture = null;
  85334. }
  85335. }
  85336. if (this._groundMirror && !newOptions.enableGroundMirror) {
  85337. this._groundMirror.dispose();
  85338. this._groundMirror = null;
  85339. }
  85340. if (this._scene.environmentTexture) {
  85341. if (this._options.environmentTexture != newOptions.environmentTexture) {
  85342. this._scene.environmentTexture.dispose();
  85343. }
  85344. }
  85345. this._options = newOptions;
  85346. this._setupBackground();
  85347. this._setupImageProcessing();
  85348. };
  85349. /**
  85350. * Sets the primary color of all the available elements.
  85351. * @param color
  85352. */
  85353. EnvironmentHelper.prototype.setMainColor = function (color) {
  85354. if (this.groundMaterial) {
  85355. this.groundMaterial.primaryColor = color;
  85356. }
  85357. if (this.skyboxMaterial) {
  85358. this.skyboxMaterial.primaryColor = color;
  85359. }
  85360. if (this.groundMirror) {
  85361. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  85362. }
  85363. };
  85364. /**
  85365. * Setup the image processing according to the specified options.
  85366. */
  85367. EnvironmentHelper.prototype._setupImageProcessing = function () {
  85368. if (this._options.setupImageProcessing) {
  85369. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  85370. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  85371. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  85372. this._setupEnvironmentTexture();
  85373. }
  85374. };
  85375. /**
  85376. * Setup the environment texture according to the specified options.
  85377. */
  85378. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  85379. if (this._scene.environmentTexture) {
  85380. return;
  85381. }
  85382. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  85383. this._scene.environmentTexture = this._options.environmentTexture;
  85384. return;
  85385. }
  85386. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  85387. this._scene.environmentTexture = environmentTexture;
  85388. };
  85389. /**
  85390. * Setup the background according to the specified options.
  85391. */
  85392. EnvironmentHelper.prototype._setupBackground = function () {
  85393. if (!this._rootMesh) {
  85394. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  85395. }
  85396. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  85397. var sceneSize = this._getSceneSize();
  85398. if (this._options.createGround) {
  85399. this._setupGround(sceneSize);
  85400. this._setupGroundMaterial();
  85401. this._setupGroundDiffuseTexture();
  85402. if (this._options.enableGroundMirror) {
  85403. this._setupGroundMirrorTexture(sceneSize);
  85404. }
  85405. this._setupMirrorInGroundMaterial();
  85406. }
  85407. if (this._options.createSkybox) {
  85408. this._setupSkybox(sceneSize);
  85409. this._setupSkyboxMaterial();
  85410. this._setupSkyboxReflectionTexture();
  85411. }
  85412. this._rootMesh.position.x = sceneSize.rootPosition.x;
  85413. this._rootMesh.position.z = sceneSize.rootPosition.z;
  85414. this._rootMesh.position.y = sceneSize.rootPosition.y;
  85415. };
  85416. /**
  85417. * Get the scene sizes according to the setup.
  85418. */
  85419. EnvironmentHelper.prototype._getSceneSize = function () {
  85420. var groundSize = this._options.groundSize;
  85421. var skyboxSize = this._options.skyboxSize;
  85422. var rootPosition = this._options.rootPosition;
  85423. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  85424. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85425. }
  85426. var sceneExtends = this._scene.getWorldExtends();
  85427. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  85428. if (this._options.sizeAuto) {
  85429. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  85430. this._scene.activeCamera.upperRadiusLimit) {
  85431. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  85432. skyboxSize = groundSize;
  85433. }
  85434. var sceneDiagonalLenght = sceneDiagonal.length();
  85435. if (sceneDiagonalLenght > groundSize) {
  85436. groundSize = sceneDiagonalLenght * 2;
  85437. skyboxSize = groundSize;
  85438. }
  85439. // 10 % bigger.
  85440. groundSize *= 1.1;
  85441. skyboxSize *= 1.5;
  85442. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  85443. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  85444. }
  85445. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85446. };
  85447. /**
  85448. * Setup the ground according to the specified options.
  85449. */
  85450. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  85451. var _this = this;
  85452. if (!this._ground) {
  85453. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  85454. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  85455. this._ground.parent = this._rootMesh;
  85456. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  85457. }
  85458. this._ground.receiveShadows = this._options.enableGroundShadow;
  85459. };
  85460. /**
  85461. * Setup the ground material according to the specified options.
  85462. */
  85463. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  85464. if (!this._groundMaterial) {
  85465. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  85466. }
  85467. this._groundMaterial.alpha = this._options.groundOpacity;
  85468. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  85469. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  85470. this._groundMaterial.primaryLevel = 1;
  85471. this._groundMaterial.primaryColor = this._options.groundColor;
  85472. this._groundMaterial.secondaryLevel = 0;
  85473. this._groundMaterial.tertiaryLevel = 0;
  85474. this._groundMaterial.useRGBColor = false;
  85475. this._groundMaterial.enableNoise = true;
  85476. if (this._ground) {
  85477. this._ground.material = this._groundMaterial;
  85478. }
  85479. };
  85480. /**
  85481. * Setup the ground diffuse texture according to the specified options.
  85482. */
  85483. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  85484. if (!this._groundMaterial) {
  85485. return;
  85486. }
  85487. if (this._groundTexture) {
  85488. return;
  85489. }
  85490. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  85491. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  85492. return;
  85493. }
  85494. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  85495. diffuseTexture.gammaSpace = false;
  85496. diffuseTexture.hasAlpha = true;
  85497. this._groundMaterial.diffuseTexture = diffuseTexture;
  85498. };
  85499. /**
  85500. * Setup the ground mirror texture according to the specified options.
  85501. */
  85502. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  85503. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85504. if (!this._groundMirror) {
  85505. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  85506. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  85507. this._groundMirror.anisotropicFilteringLevel = 1;
  85508. this._groundMirror.wrapU = wrapping;
  85509. this._groundMirror.wrapV = wrapping;
  85510. this._groundMirror.gammaSpace = false;
  85511. if (this._groundMirror.renderList) {
  85512. for (var i = 0; i < this._scene.meshes.length; i++) {
  85513. var mesh = this._scene.meshes[i];
  85514. if (mesh !== this._ground &&
  85515. mesh !== this._skybox &&
  85516. mesh !== this._rootMesh) {
  85517. this._groundMirror.renderList.push(mesh);
  85518. }
  85519. }
  85520. }
  85521. }
  85522. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  85523. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  85524. };
  85525. /**
  85526. * Setup the ground to receive the mirror texture.
  85527. */
  85528. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  85529. if (this._groundMaterial) {
  85530. this._groundMaterial.reflectionTexture = this._groundMirror;
  85531. this._groundMaterial.reflectionFresnel = true;
  85532. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  85533. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  85534. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  85535. }
  85536. };
  85537. /**
  85538. * Setup the skybox according to the specified options.
  85539. */
  85540. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  85541. var _this = this;
  85542. if (!this._skybox) {
  85543. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  85544. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  85545. }
  85546. this._skybox.parent = this._rootMesh;
  85547. };
  85548. /**
  85549. * Setup the skybox material according to the specified options.
  85550. */
  85551. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  85552. if (!this._skybox) {
  85553. return;
  85554. }
  85555. if (!this._skyboxMaterial) {
  85556. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  85557. }
  85558. this._skyboxMaterial.useRGBColor = false;
  85559. this._skyboxMaterial.primaryLevel = 1;
  85560. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  85561. this._skyboxMaterial.secondaryLevel = 0;
  85562. this._skyboxMaterial.tertiaryLevel = 0;
  85563. this._skyboxMaterial.enableNoise = true;
  85564. this._skybox.material = this._skyboxMaterial;
  85565. };
  85566. /**
  85567. * Setup the skybox reflection texture according to the specified options.
  85568. */
  85569. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  85570. if (!this._skyboxMaterial) {
  85571. return;
  85572. }
  85573. if (this._skyboxTexture) {
  85574. return;
  85575. }
  85576. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  85577. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85578. return;
  85579. }
  85580. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  85581. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  85582. this._skyboxTexture.gammaSpace = false;
  85583. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85584. };
  85585. /**
  85586. * Dispose all the elements created by the Helper.
  85587. */
  85588. EnvironmentHelper.prototype.dispose = function () {
  85589. if (this._groundMaterial) {
  85590. this._groundMaterial.dispose(true, true);
  85591. }
  85592. if (this._skyboxMaterial) {
  85593. this._skyboxMaterial.dispose(true, true);
  85594. }
  85595. this._rootMesh.dispose(false);
  85596. };
  85597. /**
  85598. * Default ground texture URL.
  85599. */
  85600. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  85601. /**
  85602. * Default skybox texture URL.
  85603. */
  85604. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  85605. /**
  85606. * Default environment texture URL.
  85607. */
  85608. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  85609. return EnvironmentHelper;
  85610. }());
  85611. BABYLON.EnvironmentHelper = EnvironmentHelper;
  85612. })(BABYLON || (BABYLON = {}));
  85613. //# sourceMappingURL=babylon.environmentHelper.js.map
  85614. 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,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\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 depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\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\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\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#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\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}"};
  85615. 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}\nlightingInfo computeProjectionTexture(lightingInfo origin,sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nlightingInfo result=origin;\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec4 textureColor=texture2D(projectionLightSampler,strq.xy);\nresult.diffuse*=vec3(textureColor);\nreturn result;\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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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\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=computeProjectionTexture(info,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#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 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;\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 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);
  85616. globalObject["BABYLON"] = BABYLON;
  85617. 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 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 HighlightLayer = BABYLON.HighlightLayer;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;
  85618. 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,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,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper };